Search code examples
arraysswiftkeypaths

How to simplify Swift array initialization


This is in reference to https://stackoverflow.com/a/47765972/8833459. The following statement is given:

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

Is there an init or something else that can be done so that the following (or something similar) might also work?

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

The original statement is just too much typing! My "preferred" method currently gives the error:

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

Solution

  • The type is unnecessary:

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

    The second Foo is unnecessary.

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

    Also the first one if you do provide the type:

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

    If the major concern is typing, add a local typealias:

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