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:

Genius Scan SDK

Genius Scan SDK: Add a powerful document scanner to any iOS app. Genius Scan’s SDK features advanced image processing that’s the result of over 10 years of research and development and can be fully customized and integrated into your app with just one line of code. Mention Swift by Sundell when requesting a free demo to get a 20% discount on your license for a whole year.