Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4, keyPath get error: cannot assign to immutable expression of type 'Any'

Tags:

swift4

public struct Person {
    var fid: Int
    var name: String
}

public struct Contact {
    var fid: Int
    var name: String
}

var pks = [\Person.fid, \Person.name]
var cks = [\Contact.fid, \Contact.name]
var p = Person(fid: 10, name: "hello")
var c = Contact(fid: 11, name: "test")

c[keyPath: cks[0]] = p[keyPath: pks[0]]

I want copy Contact's values to Person use swift 4 keyPath. Get an error: cannot assign to immutable expression of type 'Any'

I don't understand why?

c[keyPath: cks[0] as! WritableKeyPath<Contact, Int>] = p[keyPath: pks[0]] as! Int 

will work. bug how can I do like this:

pks.indices.forEach { index in
    let pk = pks[index]
    let ck = cks[index]
    c[keyPath: ck] = p[keyPath: pk]
}
like image 334
user8574338 Avatar asked Dec 08 '25 22:12

user8574338


1 Answers

I'm hitting the same issue but the problem seems to be that it cannot infer writeable types when you mix them:

var mixed = [\Person.fid, \Person.name]            // [PartialKeyPath<Person>]
var ids = [\Person.fid, \Person.sid]               // [ReferenceWriteableKeyPath<Person, Int]
var mixedIds = [\Person.fid, \Contact.fid]         // [AnyKeyPath]
var strings = [\Person.firstName, \Person.surname] // [ReferenceWriteableKeyPath<Person, String>]

In theory this would work:

let person = Person()
person[keyPath:strings[0]] = strings[1]
like image 177
Tristan Warner-Smith Avatar answered Dec 12 '25 12:12

Tristan Warner-Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!