如何简化Swift数组初始化

时间:2018-06-14 18:06:43

标签: arrays swift keypaths

这是参考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]

原始声明只是打字太多了!我的首选&#34;方法目前给出错误:

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

1 个答案:

答案 0 :(得分:0)

类型是不必要的:

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