码迷,mamicode.com
首页 > 其他好文 > 详细

Swift 枚举和结构

时间:2014-06-06 08:30:54      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:des   c   style   class   blog   code   

枚举

  使用enum创建枚举——注意 Swift 的枚举可以关联方法:

bubuko.com,布布扣
 1 enum Rank: Int {
 2     case Ace = 1 case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
 3     case Jack, Queen, King
 4         func simpleDescription () -> String {
 5         switch self {
 6             case .Ace:
 7                 return "ace" case .Jack:
 8                 return "jack" case .Queen:
 9                 return "queen" case .King:
10                 return "king" default:
11                 return String (self.toRaw ())
12         }
13     }
14 }
15 let ace = Rank.Ace
16 let aceRawValue = ace.toRaw ()
bubuko.com,布布扣

使用toRawfromRaw在原始(raw)数值和枚举值之间进行转换:

bubuko.com,布布扣
1 if let convertedRank = Rank.fromRaw (3) {
2     let threeDescription = convertedRank.simpleDescription ()
3 }
bubuko.com,布布扣

注意枚举中的成员值(member value)是实际的值(actual value),和原始值(raw value)没有必然关联。

  一些情况下枚举不存在有意义的原始值,这时可以直接忽略原始值:

bubuko.com,布布扣
 1 enum Suit {
 2     case Spades, Hearts, Diamonds, Clubs
 3         func simpleDescription () -> String {
 4         switch self {
 5             case .Spades:
 6                 return "spades" case .Hearts:
 7                 return "hearts" case .Diamonds:
 8                 return "diamonds" case .Clubs:
 9                 return "clubs"
10         }
11     }
12 }
13 let hearts = Suit.Hearts
14 let heartsDescription = hearts.simpleDescription ()
bubuko.com,布布扣

除了可以关联方法,枚举还支持在其成员上关联值,同一枚举的不同成员可以有不同的关联的值:

bubuko.com,布布扣
 1 enum ServerResponse {
 2     case Result (String, String)
 3     case Error (String)
 4 }
 5 
 6 let success = ServerResponse.Result ("6:00 am", "8:09 pm")
 7 let failure = ServerResponse.Error ("Out of cheese.")
 8 
 9 switch success {
10     case let .Result (sunrise, sunset):
11         let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)." case let .Error (error):
12         let serverResponse = "Failure... \(error)"
13 }
bubuko.com,布布扣

 

结构

  Swift 使用struct关键字创建结构。结构支持构造器和方法这些类的特性。结构和类的最大区别在于:结构的实例按值传递(passed by value),而类的实例按引用传递(passed by reference)。

bubuko.com,布布扣
1 struct Card {
2     var rank: Rank
3     var suit: Suit
4     func simpleDescription () -> String {
5         return "The \(rank.simpleDescription ()) of \(suit.simpleDescription ())"
6     }
7 }
8 let threeOfSpades = Card (rank: .Three, suit: .Spades)
9 let threeOfSpadesDescription = threeOfSpades.simpleDescription ()
bubuko.com,布布扣

 

 

Swift 枚举和结构,布布扣,bubuko.com

Swift 枚举和结构

标签:des   c   style   class   blog   code   

原文地址:http://www.cnblogs.com/atong/p/3767489.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!