Function Array> -> Optional>

前端 未结 3 1837
半阙折子戏
半阙折子戏 2021-01-06 09:12

Here is what I\'m trying to do:

extension Array> {   
  func unwrap() -> Optional> {
    let a = self.flatMap         


        
3条回答
  •  北恋
    北恋 (楼主)
    2021-01-06 10:00

    Swift 4

    Inspired by the solution by @findall, 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)
        }
    }
    

提交回复
热议问题