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

Smart key paths

Another important change introduced by Swift 4 is that of smarter key paths. Swift key paths are strongly typed and enforce a compile time check and remove a common runtime error.

You write a key path by starting with a backslash: `\Book.title`. Every type automatically gets a `[keyPath: …]` subscript to get or set the value at the specified key path:

struct Book {
var title = ""
let price : Float
}
let titleKeyPath = \Book.name
let mathsBook = Book(name: "Algebra", price: 10.50)
mathsBook[keyPath: titleKeyPath]

The value in the earlier mentioned keyPath is "Algebra".

The titleKeyPath object defines a citation to the name property. Then, it can be used as a subscript on that object. You can store and manipulate key paths. For example, you can append additional segments to a key path to drill down further. Key paths are composed of a root, and then you can drill down by following a combination of properties and subscripts.

If you change the variable of mathsBook from let to var, a specific property can also be modified through the keyPath subscript syntax:

mathsBook[keyPath: titleKeyPath] = "Trigonometry"
let newTitle = mathsBook[keyPath: titleKeyPath]

The value in the mentioned keyPath is "Trigonometry".

主站蜘蛛池模板: 辽阳市| 盈江县| 聂拉木县| 富蕴县| 正安县| 雅江县| 尼玛县| 贡觉县| 翼城县| 东乌珠穆沁旗| 浦北县| 渝北区| 五华县| 喜德县| 宁远县| 五莲县| 祁门县| 南平市| 仙居县| 南开区| 巩留县| 浦城县| 通道| 巧家县| 潼南县| 磐安县| 遵义市| 建阳市| 大渡口区| 阜平县| 施甸县| 遂昌县| 荥经县| 抚远县| 秭归县| 平顶山市| 大渡口区| 临武县| 安乡县| 克什克腾旗| 达拉特旗|