我正在通过苹果的应用程序开发手册快速学习。有一个项目用于设计最喜欢的运动员应用程序,以查看、添加和编辑运动员。
我想知道是否有办法在结构/类中拥有一个依赖于另一个变量的文本的类型的变量。。。。
好吧,这就是我的想法。
enum League {
case MLB, NFL, NBA
}
enum MLB {
case Braves, Yankees, Red Sox
}
enum NFL {
case Falcons, Giants, Patriots
}
enum NBA {
case Hawks, Knicks, Celtics
}
struct Athlete {
var name: String
var age: Int
var league: League
var Team: switch league{
case .MLB:
return MLB enum
case .NFL:
return NFL enum
case .NBA:
return NBA enum
}
}
最佳答案
枚举案例中不能有空格。按照惯例,你应该使用小写字母。从你的代码来看,你似乎在寻找这样的东西:
enum League {
case mlb, nfl, nba
}
protocol LeagueTeam {
static var league: League { get }
}
enum MLBTeams: LeagueTeam {
case braves, yankees, redSox
static let league = League.mlb
}
enum NFLTeams: LeagueTeam {
case falcons, giants, patriots
static let league = League.nfl
}
enum NBATeams: LeagueTeam {
case hawks, knicks, celtics
static let league = League.nba
}
struct Athlete {
var name: String
var age: Int
var team: LeagueTeam
var league: League { return type(of: team).league }
}