簡體   English   中英

Swift:具有多個類型選項的未聲明變量

[英]Swift: Undeclared Variable with Multiple Type Options

我正在學習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
    } 
}

枚舉情況下不能有空格。 按照約定,您應該使用lowerCamelCase。 僅僅通過查看您的代碼,就好像您在尋找這樣的東西:

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 }
}

我喜歡Alexander的解決方案,但這也很適合與關聯數據進行枚舉:

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
        }
    }
}

要獲得Alexander的解決方案在LeagueTeam上允許== LeagueTeam 使LeagueTeam符合Equatable會產生各種問題,並且您不能對LeagueTeam進行詳盡的switch ,因為它可以具有任意實現。 因此,在此處使用枚舉是一件好事。

另一方面,使用枚舉會使您進入詳盡的切換語句,如果聯盟或球隊名單可能更改,則可能會出現問題。 (另一方面,這可能是一個好處……)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM