TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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      

Hacking with Swift is sponsored by Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn 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.