1
성장하고 확장 할 switch 문과는 대조적으로 Array의 확장으로이 작업을 수행 할 수 있습니까? 이 작동합니다 스위치 방식 Swift: Test class type in switch statement조건부 추가를 위해 스위프트 배열에 확장을 추가하는 방법?
성장하고 확장 할 switch 문과는 대조적으로 Array의 확장으로이 작업을 수행 할 수 있습니까? 이 작동합니다 스위치 방식 Swift: Test class type in switch statement조건부 추가를 위해 스위프트 배열에 확장을 추가하는 방법?
에서 온 :
exteriorColorOptions.appendIfPossible(option)
otherOptions.appendIfPossible(option)
참고 :
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
}
}
난 그냥 장소의 오른쪽 확장자로 다음을 수행 할 수 있도록하고 싶습니다
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]