Key Path Expressions as Functions

able to use the key path expression \Root.value wherever functions of (Root) -> Value are allowed. Swift 5.2

๐Ÿ‘‰ paiza.io

struct User {
    let email: String
    let isActive: Bool
}

let users = [
    User(email: "joe@me.com", isActive: true),
    User(email: "joy@me.com", isActive: false)
]

// โญ๏ธ key path as functions
// 1. \.email    = { $0.email    }
// 2. \.isActive = { $0.isActive }
//                     โ•ญโ”€โ”€1โ”€โ”€โ•ฎ
let emails = users.map(\.email)    // (User) -> String
// ["joe@me.com", "joy@me.com"]

//                             โ•ญโ”€โ”€โ”€2โ”€โ”€โ”€โ”€โ•ฎ
let activeUsers = users.filter(\.isActive)    // (User) -> Bool
// [User(email: "joe@me.com", isActive: true)]

// โญ๏ธ subscript <---> key path 
// user[keyPath: \User.isActive] == user.isActive 
// let userStates = users.map { user in user[keyPath: \User.isActive] } // == users.map { $0.isActive }
     

Last updated