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)

Support Swift by Sundell by checking out this sponsor:

Bitrise

Bitrise: Kick off 2022 by easily setting up fast, rock-solid continuous integration for your project with Bitrise. In just a few minutes, you can set up builds, tests, and automatic App Store and beta deployments for your project, all running in the cloud on every pull request and commit. Try it for free today.