read

Summary of what’s new in Foundation, Swift 4, from session 212. Tip: You can download WWDC videos easily with wwdc-dl.

Key Paths

Apple calls it Smart, because it is statically safe, and fast.

It is built into Swift language, with a single \

// To get via keypath
let age = ben[keyPath: \Kid.age]

// To set via keypaht
ben[keyPath: \Kid.nickname] = "Ben"

Appending Key Paths

You can append key path, provided the type you “chain” is the same.

So if you append, the final keypath is simply of type Keypath<BirthdayParty, Double>.

There are more keypath types.

Key-Value Observation

// To use
let observation = mia.observe(\.age) { observed, change in
  // observed is the updated "mia"
}

Codable/JSON

Swift also finally recognize the importance of JSON.

You simply add the trait protocol Codable to your model, and it will work (because of default protocol extension).

If you want to customize the key names, you can simply add your own CodingKeys as an enum in your model. See how the camel case “comment_count” is customized:

private enum CodingKeys : String, CodingKey {
    case author
    case commentCount = "comment_count"
}

Ok, actually Codable is not only for JSON data, but for other formats like Property List too. There is JSONDecoder, and also PropertyListDecoder


Image

@samwize

¯\_(ツ)_/¯

Back to Home