小编vor*_*tek的帖子

为什么在已定义所有类型时需要通用?

练习是编写我自己的map()函数Collection(不使用任何功能原语,如reduce()).它应该处理这样的情况:

func square(_ input: Int) -> Int {
            return input * input
        }
let result = input.accumulate(square) // [1,2,3] =>  [1,4,9]
Run Code Online (Sandbox Code Playgroud)

我的第一次尝试是:

extension Collection {
    func accumulate(_ transform: (Element) -> Element) -> [Element] {

        var array: [Element] = []
        for element in self {
            array.append(transform(element))
        }
        return array
    }
}    
Run Code Online (Sandbox Code Playgroud)

这在游乐场中运行良好,但无法针对测试构建,给出错误:

Value of type '[Int]' has no member 'accumulate'
Run Code Online (Sandbox Code Playgroud)

解决方案是将accumulate方法泛化:

extension Collection {
    func accumulate<T>(_ transform: (Element) -> T) -> [T] { …
Run Code Online (Sandbox Code Playgroud)

generics swift

11
推荐指数
1
解决办法
405
查看次数

标签 统计

generics ×1

swift ×1