我试图为Swift数组添加附加重载
import Foundation
extension Array {
func append<From>(from: [From], transformer: (From) -> [Element]) {
from.forEach {
self.append(contentsOf: transformer($0))
}
}
}
它向我显示了编译错误:Error:(47, 24) extraneous argument label 'contentsOf:' in call
看来我无法在自己的重载中使用其他的append重载。真的很奇怪你能帮忙吗?
答案 0 :(得分:2)
该错误具有误导性。您的append
函数需要标记为mutating
:
extension Array {
mutating func append<From>(from: [From], transformer: (From) -> [Element]) {
from.forEach {
self.append(contentsOf: transformer($0))
}
}
}
替代实施
(这可能不是您所需要的,但可以帮助其他用户。)
如果将transformer
设置为(From) -> Element
,则可以简化为:
extension Array {
mutating func append<From>(from: [From], transformer: (From) -> Element) {
self.append(contentsOf: from.map(transformer))
}
}
示例呼叫:
var strings = ["a", "b", "c"]
strings.append(from: [1, 2, 3], transformer: String.init)
print(strings) // prints ["a", "b", "c", "1", "2", "3"]