Articles, podcasts and news about Swift development, by John Sundell.

Passing key paths as functions

Published on 06 Feb 2020

New in Swift 5.2: Key path literals can now be passed as functions. This might be a small change in the grand scheme of things, but it really makes closures in which we’re simply accessing a property read so much nicer — since we can now pass that property’s key path directly:

struct Movie {
    var name: String
    var isFavorite: Bool
    ...
}

let movies: [Movie] = loadMovies()

// Equivalent to movies.map { $0.name }
let movieNames = movies.map(\.name)

// Equivalent to movies.filter { $0.isFavorite }
let favoriteMovies = movies.filter(\.isFavorite)