在这里,我有一个名为Player的类,该类的变量类型为Sport,可以是Basketball或Soccer。我希望能够在Player声明中声明Sport的类型。有什么建议么?
class Soccer : Sport {
override var players : Int { get { return 11 } }
}
class Basketball : Sport {
override var players : Int { get { return 5 } }
}
class Sport {
var teamName: String
var players: Int { get { return 0 } }
init(teamName: String) {
self.teamName = teamName
}
}
class Player {
let sport : Sport?
init? (typeOfSport: Soccer, teamName: String) {
self.sport = Soccer(teamName: teamName)
}
init? (typeOfSport: Basketball, teamName: String) {
self.sport = Basketball(teamName: teamName)
}
}
let me = Player(typeOfSport: Soccer(), teamName: "chelsea")
let him = Player(typeOfSport: Basketball(), teamName: "wizards")
最佳答案
您也可以像这样使用枚举:
enum Sport {
case Soccer (teamName : String)
var players: Int {
switch self{
case .Soccer: return 11
default: return 0
}
}
}
class Player {
let sport: Sport?
init? (s : Sport){
self.sport = s
}
}
Sport.Soccer (teamName: "Cambuur").players
关于ios - 在单独的类中声明变量的类类型[Swift],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29016631/