In Swift, I have a custom struct with this basic premise:
A wrapper struct that can contain any type that conforms to BinaryInteger
suc
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 })
}
}