• 周四. 12月 1st, 2022

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Swift 枚举和结构

admin

11月 28, 2021

枚举

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

 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 ()

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

1 if let convertedRank = Rank.fromRaw (3) {
2     let threeDescription = convertedRank.simpleDescription ()
3 }

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

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

 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 ()

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

 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 }

结构

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

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 ()

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注