我在这篇文章 (https://www.uraimo.com/2016/01/06/10-Swift-One-Liners-To-Impress-Your-Friends/) 中对 Xcode 9 beta 2 Swift 4 做了一些练习,当时我在执行第 1 项时遇到错误。 6:
extension Sequence{
typealias Element = Self.Iterator.Element
func partitionBy(fu: (Element)->Bool)->([Element],[Element]){
var first=[Element]()
var second=[Element]()
for el in self {
if fu(el) {
first.append(el)
}else{
second.append(el)
}
}
return (first,second)
}
}
Xcode 9 在以下行中抛出错误:
var first=[Element]()
var second=[Element]()
完整错误如下:
error: Swift-Playground.playground:6:29: error: cannot call value of non-function type '[Self.Element.Type]'
var second=[Element]()
即使我删除类型别名并使用完整的 Self.Iterator.Element
类型,错误仍然存在。
这段代码在 Swift 3 上完美运行。我看不出为什么它不能在 Swift 4 上运行。有人可以帮我解决一下 Swift 4 在处理关联类型方面的变化吗?如果是的话,还有什么选择实例化数组。
最佳答案
在 Swift 4 中,protocol Sequence
已经定义了
associatedtype Element where Self.Element == Self.Iterator.Element
所以你可以删除
typealias Element = Self.Iterator.Element
让它编译。</p>
关于 swift 4 : Cannot call value of non-function type '[Self.Element.Type]' when instantiating associated type array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44858225/