小编ste*_*tef的帖子

Swift 4:扩展数组<Optional <SomeType <T >>>生成数组<Optional <T >>可能吗?

在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)

arrays generics optional swift swift-extensions

5
推荐指数
2
解决办法
708
查看次数

标签 统计

arrays ×1

generics ×1

optional ×1

swift ×1

swift-extensions ×1