- Swift 4 Programming Cookbook
- Keith Moon
- 329字
- 2021-07-08 10:21:28
Associated values
Our string-based enum seems perfect for our title information, except that we have a case called other. If the person has a title that we hadn't considered when defining the enum, we can select other, but that doesn't capture what the other title is. We will need to define a whole other property to hold the value of the other title, but there would be nothing to force it to be used when the other case is selected, and nothing to stop it from being used when a different Title case is selected.
Swift enums have a solution for this situation--associated values; we can choose to associate a value with each enum case, allowing us to bind a non-optional string to our other case.
Let's rewrite our Title enum to use an associated value:
enum Title {
case mr
case mrs
case mister
case miss
case dr
case prof
case other(String)
}
We have defined the other case to have an associated value by putting the value's type in brackets after the case declaration. We do not need to add associated values wholesale to every case; other case declarations can have associated values of a different type, or none at all.
Let's look at how we assign an enum case with an associated type:
let mister: Title = .mr
let dame: Title = .other("Dame")
The associated value is declared in brackets after the case, and the compiler enforces that the type matches the type declared in our enum definition. As we declared the other case to have a non-optional string, we are ensuring that a title of other cannot be selected without providing details of what the other title is, and we don't have an unneeded property hanging around when anything else is selected.
- .NET之美:.NET關(guān)鍵技術(shù)深入解析
- Getting Started with CreateJS
- Cassandra Design Patterns(Second Edition)
- Silverlight魔幻銀燈
- Python高效開發(fā)實戰(zhàn):Django、Tornado、Flask、Twisted(第3版)
- Yii Project Blueprints
- Python機器學(xué)習(xí):預(yù)測分析核心算法
- Spring+Spring MVC+MyBatis從零開始學(xué)
- Java Web從入門到精通(第3版)
- Web編程基礎(chǔ):HTML5、CSS3、JavaScript(第2版)
- Akka入門與實踐
- 青少年P(guān)ython趣味編程
- jMonkeyEngine 3.0 Cookbook
- Visual FoxPro程序設(shè)計(第二版)
- HTML5與CSS3權(quán)威指南(第2版·下冊)