gpt4 book ai didi

swift4 - Swift 4,keyPath 出现错误 : cannot assign to immutable expression of type 'Any'

转载 作者:行者123 更新时间:2023-12-01 13:30:38 31 4
gpt4 key购买 nike

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]]

我想使用 swift 4 keyPath 将 Contact 的值复制到 Person。得到一个 错误:无法分配给“任何”类型的不可变表达式

我不明白为什么?

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

会起作用。错误我怎么能这样做:

pks.indices.forEach { index in
let pk = pks[index]
let ck = cks[index]
c[keyPath: ck] = p[keyPath: pk]
}

最佳答案

我遇到了同样的问题,但问题似乎是当您混合使用它们时它无法推断出可写类型:

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>]

理论上这可行:

let person = Person()
person[keyPath:strings[0]] = strings[1]

关于swift4 - Swift 4,keyPath 出现错误 : cannot assign to immutable expression of type 'Any' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46095758/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com