Reputation: 9248
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
Upvotes: 1
Views: 1573
Reputation: 23
Actually the answer is correct but maybe not exactly what you want:
extension Array {
mutating func safeAppend(newElement: Element?) {
if let element = newElement {
append(element)
}
}
This one will throw a compile time error in case you try appending an element thats not of the arrays original type.
E.g. you will see an error if you try to append an Int
to an array of string [String]
.
Upvotes: 0
Reputation: 539715
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]
Upvotes: 1