如何将 KeyPath<CNContact、Array<CNLabeledValue>>转换为 KeyPath<CNContact, Any>

How to cast KeyPath<CNContact, Array<CNLabeledValue>> to KeyPath<CNContact, Any>

提问人:daniel 提问时间:6/30/2023 更新时间:6/30/2023 访问量:15

问:

我需要将 KeyPath 值放在 Array<KeyPath<CNContact,Any>> 类型的数组中。但是,\CNContact.phoneNumbers 无法强制转换为 KeyPath<CNContact,Any>。

这是我的测试代码:

let keyPath0: KeyPath<CNContact,Any> = \CNContact.phoneNumbers // Runtime error message: Key path value type '[CNLabeledValue<CNPhoneNumber>]' cannot be converted to contextual type 'Any'

let keyPath: KeyPath<CNContact,Any> = \CNContact.phoneNumbers as! KeyPath<CNContact,Any> // Warning message: Cast from 'KeyPath<CNContact, [CNLabeledValue<CNPhoneNumber>]>' to unrelated type 'KeyPath<CNContact, Any>' always fails

数组 swift cast swift-keypath

评论

0赞 vadian 6/30/2023
of 是表示一种具体类型的泛型。它不可能是.ValueKeyPathAny
0赞 Rob Napier 6/30/2023
我可以.但随后是. 是与 不同的类型。这里要求的东西是不可能的。KeyPath 需要知道其类型。(如果该类型是 Any,那没关系,但从字面上看,这意味着 Any,而不是“我不在乎它是什么类型。AnyAny[CNLabeledValue<CNPhoneNumber>]Any
0赞 daniel 6/30/2023
@RobNapier 那么,如何将 KeyPath<CNContact,String> 和 KeyPath<CNContact,Array<CNLabeledValue>>包含在同一个数组中呢?
1赞 Rob Napier 6/30/2023
[PartialKeyPath<CNContact>]

答: 暂无答案