如何简化Swift数组初始化

How to simplify Swift array initialization

这是参考 。 给出如下语句:

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

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

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

原来的说法是打字太多了!我的 "preferred" 方法当前给出错误:

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