UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Given an array of structs with non-optional properties, why is compactMap { $0.property } fine but compactMap(\.property) doesn't work?

Forums > Swift

struct Person {
    let name: String
}

let persons = [
    Person(name: "Mark"),
    Person(name: "Emma"),
]

let mapped1 = persons.compactMap { $0.name }
print(mapped1)

//let mapped2 = persons.compactMap(\.name)
//print(mapped2)

Here I get the expected print output ["Mark", "Emma"].

But when I uncomment the commented lines I get the error

error: Playground.playground:13:34: error: key path value type 'String' cannot be converted to contextual type 'String?'

let mapped2 = persons.compactMap(.name)

Why can compactMap deal just fine with the non-optional strings in the case of { $0.name } but the KeyPath version doesn't work?

3      

I assume it has to do with the fact that a keypath of type \Root.value can be used where a function like (Root) -> Value is expected, so in this instance \.name is the equivalent of (Person) -> String but compactMap is expecting a function like (Person) -> String?

But I don't know for certain, given that this works:

func getName(_ person: Person) -> String {
    person.name
}

let mapped3 = persons.compactMap(getName)
print(mapped3)
//prints ["Mark", "Emma"]

This might be better asked at the Swift forums. They can usually get into the nitty gritty technical details about this kind of thing.

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.