如何向 Swift 数组添加扩展以有条件地追加?

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

有没有一种方法可以将此作为 Array 的扩展,而不是不断增长的 switch 语句?

    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
        }
    }

我希望能够使用正确的扩展名执行以下操作:

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

注:切换方法来自 Swift: Test class type in switch statement

这应该有效:

extension Array {

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

条件转换 newElement as? Element 如果 新元素符合数组元素类型 Element.

(的子类)或者是其实例

示例:

class A {}
class B: A {}
class C {}

var array: [A] = []

array.appendIfPossible(newElement: B())
print(array) // [B]

array.appendIfPossible(newElement: C())
print(array) // [B]

实际上答案是正确的,但可能不是您想要的:

  extension Array {
    mutating func safeAppend(newElement: Element?) {
      if let element = newElement {
        append(element)
    }
  }

如果您尝试附加一个不是数组原始类型的元素,这将引发编译时错误。

例如如果您尝试将 Int 附加到字符串数组 [String].

,您将看到一个错误