How to use the key path as functions in Swift 5+?

Uplift iOS Interview

The Guide is for YOU if
  • You are preparing for an iOS interview and want to improve your skills and knowledge and looking to level up your interview game and land your dream job.
  • You want to gain confidence and ease during iOS interviews by learning expert tips and curated strategies.
  • You want access to a comprehensive list of iOS interview QA to practice and prepare.

From Swift 5.2 key path can be passed as functions. Using key path closures seems much more simpler and readable.

struct Food {
    let name: String
    let isHot: Bool
    let origin: String
}

let foods: [Food] = some foods here

let foodNames = foods.map(\.name)
// Same as foods.map { $0.name }
// These ad hoc closures are short and sweet but 
// Swift already has a shorter and sweeter syntax 
// that can describe this: key paths. 

let hotFoods = foods.filter(\.isHot)
// Same as foods.filter { $0.isHot }


✍️ Written by Ishtiak Ahmed

👉 Follow me on XLinkedIn



Get Ready to Shine: Mastering the iOS Interview




Enjoying the articles? Get the inside scoop by subscribing to my newsletter.

Get access to exclusive iOS development tips, tricks, and insights when you subscribe to my newsletter. You'll also receive links to new articles, app development ideas, and an interview preparation mini book.

If you know someone who would benefit from reading this article, please share it with them.