Search code examples
arraysswiftgenericsswift3generic-collections

How to Add an Extension to Swift Array To Conditionally Append?


Is there a way to do this as an extension to Array as opposed to a switch statement that's going to grow and grow?

    fileprivate var exteriorColorOptions = [ExteriorColorOption]()
    fileprivate var otherOptions = [SomeOtherOption]()
      : more options

    func add(option:FilteredOption) {

        switch(option) {
        case let thing as ExteriorColorOption:
                exteriorColorOptions.append(thing)
        case and on and on
        default:
            break
        }
    }

I would like to be able to just do the following with the right extension in place:

exteriorColorOptions.appendIfPossible(option)
otherOptions.appendIfPossible(option)

Note: switch approach came from Swift: Test class type in switch statement


Solution

  • This should work:

    extension Array {
    
        mutating func appendIfPossible<T>(newElement: T) {
            if let e = newElement as? Element {
                append(e)
            }
        }
    }
    

    The conditional cast newElement as? Element succeeds if the new element conforms to or is an instance of (a subclass of) the arrays element type Element.

    Example:

    class A {}
    class B: A {}
    class C {}
    
    var array: [A] = []
    
    array.appendIfPossible(newElement: B())
    print(array) // [B]
    
    array.appendIfPossible(newElement: C())
    print(array) // [B]