I have a question regarding the Swift Subscription issue.

Asked 2 years ago, Updated 2 years ago, 28 views

It's a problem.

You must create a subscription below the comments. First of all, what I thought was

I don't know how to implement it, but I'm trying to approach it. The part where I don't have a clue is

I think so. I still have a long way to go, so I have to study more, but I'm nervous because it's not working out.

I ask for your help me.

import UIKit

struct Player {
    let number: Int
    let name: String
}

struct Team {
    let name: String
    let squad: [Player]

    // Please implement your subscription here.
}

// Please do not modify the code below.
let firstTeam = [
    Player(number: 1, name: "Hugo Lloris"),
    Player(number: 3, name: "Danny Rose"),
    Player(number: 4, name: "Toby Alderweireld"),
    Player(number: 5, name: "Jan Vertonghen"),
    Player(number: 7, name: "Heung-Min Son"),
    Player(number: 10, name: "Harry Kane"),
    Player(number: 12, name: "Victor Wanyama"),
    Player(number: 20, name: "Dele Alli"),
    Player(number: 23, name: "Christian Eriksen"),
    Player(number: 33, name: "Ben Davies")
]
let tot = Team(name: "Tottenham Hotspur", squad: firstTeam)


var name: String?
var number: Int?

if let player = tot[7] {
    name = player.name
}

if let player = tot["David de Gea"] {
    number = player.number
}

print(name == .some("Heung-Min Son") && number == nil)

swift

2022-09-21 12:37

1 Answers

I studied and solved it. I'm not sure if it's the answer that the question asks for, but the given test passes.


struct Team {
    let name: String
    let squad: [Player]

    // TODO: Please implement your subscription here.
    //---------------------------------------------
    subscript(number: Int) -> Player? {
        for player in squad {
            if player.number == number {
                return player
            }
        }
        return nil
    }

    subscript(name: String) -> Player? {
        for player in squad {
            if player.name == name {
                return player
            }
        }
        return nil
    }
    //---------------------------------------------
}


2022-09-21 12:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.