Swift學習4---枚舉和結構體

來源:互聯網
上載者:User

標籤:

1.枚舉

  使用enum建立枚舉——注意Swift的枚舉可以關聯方法:

enum Rank: Int {    case Ace = 1    case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten    case Jack, Queen, King    func simpleDescription() -> String {        switch self {        case .Ace:            return "ace"        case .Jack:            return "jack"        case .Queen:            return "queen"        case .King:            return "king"        default:            return String(self.rawValue)        }    }}

let ace = Rank.Ace

let aceRawValue = ace.rawValue

  使用rawValue在原始(raw)數值和枚舉值之間進行轉換:

if let convertedRank = Rank(rawValue: 3) {    let threeDescription = convertedRank.simpleDescription()}

  注意枚舉中的成員值(member value)是實際的值(actual value),和原始值(raw value)沒有必然關聯。

  枚舉的成員值是實際值,並不是原始值的另一種表達方法。實際上,如果原始值沒有意義, 你不需要設定 

enum Suit {    case Spades, Hearts, Diamonds, Clubs    func simpleDescription() -> String {        switch self {        case .Spades:            return "spades"        case .Hearts:            return "hearts"        case .Diamonds:            return "diamonds"        case .Clubs:            return "clubs"        }    }}let hearts = Suit.Heartslet heartsDescription = hearts.simpleDescription()

  除了可以關聯方法,枚舉還支援在其成員上關聯值,同一枚舉的不同成員可以有不同的關聯的值:

enum ServerResponse {    case Result(String, String)    case Error(String)}let success = ServerResponse.Result("6:00 am", "8:09 pm")let failure = ServerResponse.Error("Out of cheese.")switch success {    case let .Result(sunrise, sunset):        let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."    case let .Error(error):        let serverResponse = "Failure... \(error)"}

2.結構體

  Swift使用struct關鍵字建立結構體。結構體支援構造器和方法這些類的特性。結構體和類的最大區別在於:結構的執行個體按值傳遞(passed by value),而類的執行個體按引用傳遞(passed by reference)。

struct Card {    var rank: Rank    var suit: Suit    func simpleDescription() -> String {        return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"    }}let threeOfSpades = Card(rank: .Three, suit: .Spades)let threeOfSpadesDescription = threeOfSpades.simpleDescription()

 

Swift學習4---枚舉和結構體

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.