官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 丰都县| 阳东县| 新兴县| 旬阳县| 宜宾市| 鹤壁市| 大城县| 马尔康县| 甘南县| 靖远县| 栖霞市| 武川县| 云南省| 天台县| 西青区| 雅江县| 祁门县| 富蕴县| 云安县| 桑日县| 武川县| 邹平县| 乌鲁木齐县| 田阳县| 乌鲁木齐县| 晋江市| 边坝县| 抚顺市| 滁州市| 池州市| 涟水县| 永定县| 全南县| 紫阳县| 璧山县| 东安县| 鄱阳县| 洛阳市| 高清| 南涧| 湘潭市|