Creating an extension to filter nils from an Array in Swift

前端 未结 7 637
难免孤独
难免孤独 2020-11-29 04:12

I\'m trying to write an extension to Array which will allow an array of optional T\'s to be transformed into an array of non-optional T\'s.

e.g. this could be writte

相关标签:
7条回答
  • 2020-11-29 04:37

    Swift 4

    This works with Swift 4:

    protocol OptionalType {
        associatedtype Wrapped
        var optional: Wrapped? { get }
    }
    
    extension Optional: OptionalType {
        var optional: Wrapped? { return self }
    }
    
    extension Sequence where Iterator.Element: OptionalType {
        func removeNils() -> [Iterator.Element.Wrapped] {
            return self.flatMap { $0.optional }
        }
    }
    

    Test:

    class UtilitiesTests: XCTestCase {
        
        func testRemoveNils() {
            let optionalString: String? = nil
            let strings: [String?] = ["Foo", optionalString, "Bar", optionalString, "Baz"]
            XCTAssert(strings.count == 5)
            XCTAssert(strings.removeNils().count == 3)
            let integers: [Int?] = [2, nil, 4, nil, nil, 5]
            XCTAssert(integers.count == 6)
            XCTAssert(integers.removeNils().count == 3)
        }
    }
    
    0 讨论(0)
提交回复
热议问题