我在这篇文章(https://www.uraimo.com/2016/01/06/10-Swift-One-Liners-To-Impress-Your-Friends/)的xcode 9 beta 2 swift 4上做了一些练习,在做第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]()

即使删除typealias并使用完整的Self.Iterator.Element类型,错误仍然存在。
此代码在Swift 3上非常有效。我看不出它为什么不能在Swift4上工作。如果Swift4在处理关联类型方面发生了变化,有人能帮我吗?如果是这样,实例化数组的替代方法是什么?

最佳答案

在Swift 4中,protocol Sequence已经定义了

associatedtype Element where Self.Element == Self.Iterator.Element

所以你可以把
typealias Element = Self.Iterator.Element

使其编译。

关于swift - Swift 4:实例化关联类型数组时无法调用非函数类型'[Self.Element.Type]'的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44858225/

10-14 18:52
查看更多