Swift: Extension on [?] to produce [?] possible?

前端 未结 2 634
傲寒
傲寒 2021-01-13 02:44

In Swift, I have a custom struct with this basic premise:

A wrapper struct that can contain any type that conforms to BinaryInteger suc

2条回答
  •  天涯浪人
    2021-01-13 03:32

    I don't know if there is a simpler solution now, but you can use the same “trick” as in How can I write a function that will unwrap a generic property in swift assuming it is an optional type? and Creating an extension to filter nils from an Array in Swift, the idea goes back to this Apple Forum Thread.

    First define a protocol to which all optionals conform:

    protocol OptionalType {
        associatedtype Wrapped
        var asOptional: Wrapped? { get }
    }
    
    extension Optional : OptionalType {  
        var asOptional: Wrapped? {  
            return self 
        }  
    }  
    

    Now the desired extension can be defined as

    extension Collection where Element: OptionalType, Element.Wrapped: SomeTypeProtocol {
        var values: [Element.Wrapped.NumberType?] {
            return self.map( { $0.asOptional?.value })
        }
    }
    

    and that works as expected:

    let arr = [SomeType(value: 123), nil, SomeType(value: 456)]
    let v = arr.values
    
    print(v) // [Optional(123), Optional(456)]
    print(type(of: v)) // Array>
    

提交回复
热议问题