我正在通过Apple的App Development一书快速学习。有一个项目用于设计最喜欢的运动员应用程序来查看、添加和编辑运动员。
我想知道是否有办法在结构/类中拥有一个依赖于另一个变量文字类型的变量......
好的,这就是我的想法。
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
}
}
枚举大小写中不能有空格。按照惯例,您应该使用较小的CamelCase。仅从您的代码来看,您似乎正在寻找类似这样的东西:
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 }
}
亚历山大的解决方案,但这也非常适合带有相关数据的枚举:
enum MLBTeam {
case braves, yankees, redSox
}
enum NFLTeam {
case falcons, giants, patriots
}
enum NBATeam {
case hawks, knicks, celtics
}
enum Team {
case mlb(MLBTeam)
case nfl(NFLTeam)
case nba(NBATeam)
}
struct Athlete {
var name: String
var age: Int
var team: Team
}
let athlete = Athlete(name: "Julio Teherán", age: 26, team: .mlb(.braves))
有了这个,您可以使用 team
属性在特定球队和联赛上切换。
switch athlete.team {
case .mlb: print("Baseball")
case .nfl: print("Football")
case .nba: print("Basketball")
}
switch athlete.team {
case .mlb(.braves): print("Braves")
default: print("Not Braves")
}
Swift 4 中一件可悲的事情是,它仍然无法为具有关联值的枚举自动生成Equatable
,因此如果需要,您必须手动执行此操作。
extension Team: Equatable {
static func ==(lhs: Team, rhs: Team) -> Bool {
switch (lhs, rhs) {
case let (.mlb(lhsTeam), .mlb(rhsTeam)): return lhsTeam == rhsTeam
case let (.nfl(lhsTeam), .nfl(rhsTeam)): return lhsTeam == rhsTeam
case let (.nba(lhsTeam), .nba(rhsTeam)): return lhsTeam == rhsTeam
default: return false
}
}
}
很难让亚历山大的解决方案允许==
LeagueTeam
.使LeagueTeam
符合Equatable
会产生各种各样的问题,并且您无法在LeagueTeam
上创建详尽的switch
,因为它可以具有任意实现。所以这是在这里使用枚举的一件好事。
另一方面,使用枚举会将您推入详尽的 switch 语句,如果联赛或球队列表可能会发生变化,这可能是一个问题。(另一方面,这可能是一个好处...