- Swift 4 Programming Cookbook
- Keith Moon
- 281字
- 2021-07-08 10:21:28
Methods and computed variables
Say that it is important for us to know whether a person's title relates to a professional qualification that the person holds. Let's add a method to our enum to provide that information:
enum Title: String {
case mr = "Mr"
case mrs = "Mrs"
case mister = "Master"
case miss = "Miss"
case dr = "Dr"
case prof = "Prof"
case other // Inferred as "other"
func isProfessional() -> Bool {
return self == Title.dr || self == Title.prof
}
}
For the list of titles that we have defined, Dr and Prof relate to professional qualifications, so we have our method return true if self (the instance of the enum type this method is called on) is equal to the dr case, or equal to the prof case.
This functionality feels more appropriate as a computed property since whether it isProfessional or not is intrinsic to the enum itself, and we don't need to do much work to determine the answer. So, let's change this into a property:
enum Title: String {
case mr = "Mr"
case mrs = "Mrs"
case mister = "Master"
case miss = "Miss"
case dr = "Dr"
case prof = "Prof"
case other // Inferred as "other"
var isProfessional: Bool {
return self == Title.dr || self == Title.prof
}
}
Now, we can determine whether a title is a professional title by accessing the computed property on it:
let loganTitle = Title.mr
let xavierTitle = Title.prof
print(loganTitle.isProfessional) // false
print(xavierTitle.isProfessional) // true
We can't store new information on an enum, but being able to define methods and computed properties that provide extra information about the enum is really powerful.
- Python概率統(tǒng)計(jì)
- VMware View Security Essentials
- Spring 5.0 Microservices(Second Edition)
- 編程卓越之道(卷3):軟件工程化
- Clojure for Domain:specific Languages
- 云原生Spring實(shí)戰(zhàn)
- 游戲程序設(shè)計(jì)教程
- Learning ELK Stack
- SQL Server 2016數(shù)據(jù)庫應(yīng)用與開發(fā)習(xí)題解答與上機(jī)指導(dǎo)
- Getting Started with NativeScript
- Python機(jī)器學(xué)習(xí)算法與應(yīng)用
- Java從入門到精通(視頻實(shí)戰(zhàn)版)
- MySQL數(shù)據(jù)庫教程(視頻指導(dǎo)版)
- 虛擬現(xiàn)實(shí):引領(lǐng)未來的人機(jī)交互革命
- 歐姆龍PLC編程指令與梯形圖快速入門