Key Paths

Introduction

Welcome to the second lesson of What’s New in Swift 4. You will discover how to save time by typing less. No need to talk much. Let’s get started.

Problem

I’m tired of chaining.

Design Model

  1. struct Developer {
  2. var platform: Platform
  3. var information: Information
  4. }
  5. enum Platform {
  6. case iOS
  7. case android
  8. }
  9. struct Information {
  10. var name, strengths, motivation: String
  11. }

Create Objects

  1. let robInformation = Information(name: "Rob", strengths: "Zenness", motivation: "Change the world")
  2. let bobInformation = Information(name: "Bob", strengths: "Dryness", motivation: "None")
  3. let rob = Developer(platform: .android, information: robInformation)
  4. let bob = Developer(platform: .iOS, information: bobInformation)

Your Past

In order to access the name property, you had to chain through for each object.

  1. rob.information.name // "Rob"
  2. bob.information.name // "Bob"

However, in Swift 4, it provides an alternative that provides safety and less typing.

Introduction Swift 4 Key Paths

You may have the access/path to the property or method as shown below.

  1. let bobPlatform = bob[keyPath: \Developer.platform] // iOS
  2. let bobName = bob[keyPath: \Developer.information.name] // 'Bob"

Store Path

You may store the path and simply apply.

  1. let informationKeyPath = \Developer.information
  2. let bobInfo = bob[keyPath: informationKeyPath]
  3. let robInfo = rob[keyPath: informationKeyPath]

Append Key Path

Fortunately, you may also append more paths to the original path as long as there is one.

  1. let nameKeyPath = informationKeyPath.appending(path: \.name)
  2. bob[keyPath: nameKeyPath] // "Bob"
  3. rob[keyPath: nameKeyPath] // "Rob"

Source Code

9001_keypaths

Resources

Smart KeyPaths: Better Key-Value Coding for Swift - Apple

Conclusion

Congratulations. Remember, even if you are chaining through, you may make a single auto-completion mistake that leads to catastrophic result. Although it is a brand new feature, if you need to access Property or Method through many chainings, I recommend you to utilize the keypath API provided in Swift 4. If you want to learn much deeper, feel free to take a look at the Apple’s proposal documentation in the lecture notes.

In the following lesson, you will learn how to make subscripts generic, which isn’t that important but at least you can brag from what you’ve learned.