在Swift 4中,我有一个带有这个基本前提的自定义结构:
一个包装器结构,可以包含任何符合BinaryIntegerInt,UInt8,Int16等类型的类型.
protocol SomeTypeProtocol {
associatedtype NumberType
var value: NumberType { get set }
}
struct SomeType<T: BinaryInteger>: SomeTypeProtocol {
typealias NumberType = T
var value: NumberType
}
Run Code Online (Sandbox Code Playgroud)
收藏的扩展:
extension Collection where Element: SomeTypeProtocol {
var values: [Element.NumberType] {
return self.map { $0.value }
}
}
Run Code Online (Sandbox Code Playgroud)
例如,这很好用:
let arr = [SomeType(value: 123), SomeType(value: 456)]
// this produces [123, 456] of type [Int] since literals are Int by default
arr.values
Run Code Online (Sandbox Code Playgroud)
我想做的是完全相同的事情,但是 SomeType<T>?
let arr: [SomeType<Int>?] = [SomeType(value: 123), …Run Code Online (Sandbox Code Playgroud)