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

前端 未结 2 608
傲寒
傲寒 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:26

    Martin R's answer is a good solution. An alternative that doesn't require an extra marker protocol is this: write an unconstrained extension on Collection, and in that extension, define a generic function that's constrained to where Element == SomeType?:

    extension Collection {
        func values() -> [T?] where Element == SomeType? {
            return map( { $0?.value })
        }
    }
    

    This works:

    let arr: [SomeType?] = [SomeType(value: 123), SomeType(value: 456)]
    arr.values() // [Optional(123), Optional(456)]
    

    You'll notice that I used a func instead of a computed property. I couldn't get the generic syntax right. Isn't this supposed to work?

    extension Collection {
        // error: consecutive declarations on a line must be separated by ';'
        var values: [T?] where Element == SomeType? {
            return self.map( { $0?.value })
        }
    }
    

提交回复
热议问题