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

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.

Enums containing associated values cannot have a raw type as they are now too complex to be represented by one of these base types, so our Title enum is no longer string-based.

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.

主站蜘蛛池模板: 射洪县| 柳江县| 沂南县| 丰镇市| 迁西县| 石城县| 伊宁市| 西丰县| 玉环县| 嘉鱼县| 收藏| 东至县| 上犹县| 山东省| 孟津县| 保靖县| 韶山市| 德格县| 金阳县| 绩溪县| 伊金霍洛旗| 六枝特区| 平凉市| 商城县| 雅江县| 巴塘县| 乡宁县| 蓬溪县| 无锡市| 浑源县| 金塔县| 武穴市| 南汇区| 彩票| 凯里市| 洪湖市| 宁城县| 青铜峡市| 即墨市| 长武县| 永兴县|