Swift学习4---枚举和结构体
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.Hearts let 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()