gpt4 book ai didi

arrays - 如何简化 Swift 数组初始化

转载 作者:行者123 更新时间:2023-11-30 11:24:49 27 4
gpt4 key购买 nike

这是引用https://stackoverflow.com/a/47765972/8833459 。现声明如下:

let fooPaths: [WritableKeyPathApplicator<Foo>] = [WritableKeyPathApplicator(\Foo.bar), WritableKeyPathApplicator(\Foo.baz)]

是否可以执行 init 或其他操作,以便以下(或类似的操作)也可以工作?

let fooPaths: [WritableKeyPathApplicator<Foo>] = [\Foo.bar, \Foo.baz]

原来的语句打字太多了!我的“首选”方法当前给出错误:

error: cannot convert value of type 'WritableKeyPath<Foo, String>' to expected element type 'WritableKeyPathApplicator<Foo>'

最佳答案

该类型是不必要的:

let fooPaths = [WritableKeyPathApplicator(\Foo.bar), WritableKeyPathApplicator(\Foo.baz)]

第二个 Foo 是不必要的。

let fooPaths = [WritableKeyPathApplicator(\Foo.bar), WritableKeyPathApplicator(\.baz)]

如果您提供类型,也是第一个:

let fooPaths: [WritableKeyPathApplicator<Foo>] = [WritableKeyPathApplicator(\.bar),
WritableKeyPathApplicator(\.baz)]

如果主要关心的是输入,请添加本地类型别名:

typealias WKPA<T> = WritableKeyPathApplicator<T>
let fooPaths: [WKPA<Foo>] = [WKPA(\.bar),
WKPA(\.baz)]

关于arrays - 如何简化 Swift 数组初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50863474/

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