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

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".

主站蜘蛛池模板: 马尔康县| 桂林市| 三亚市| 中卫市| 慈溪市| 盈江县| 佛学| 乐平市| 苗栗县| 宜兴市| 确山县| 北辰区| 常熟市| 延安市| 广宗县| 闽清县| 恩施市| 普安县| 宕昌县| 临潭县| 广西| 荆门市| 威信县| 聂荣县| 桦甸市| 通江县| 宾川县| 六盘水市| 江达县| 大渡口区| 晋宁县| 平远县| 衡山县| 呼伦贝尔市| 连云港市| 宁安市| 绍兴市| 独山县| 牙克石市| 扬中市| 中方县|