2017-08-14 43 views
2

我試圖更新數學庫是用斯威夫特3兼容,但我遇到了一個錯誤:斯威夫特錯誤:「序」需要的各類「T」和「ArraySlice <T>」相當於

'Sequence' requires the types 'T' and 'ArraySlice<T>' be equivalent

Apple關於Sequence的文檔建議makeIterator()方法返回一個迭代器。而且似乎迭代器正在返回grid變量中的一個元素,其變量爲T。我不太確定我在這裏錯過了什麼。任何意見將是有益的。

回答

2

你的代碼編譯得很好,就像Swift 3.1(Xcode 8.3.3)。如夫特4(的Xcode 9,目前測試版)進行編譯時,錯誤

'Sequence' requires the types 'T' and 'ArraySlice<T>' be equivalent 

發生,因爲這時的 協議Sequence已經定義了

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

與您的定義有衝突。您可以選擇不同的 名稱爲您的類型別名,或只是將其刪除(並使用T代替):

public struct Matrix<T> where T: FloatingPoint, T: ExpressibleByFloatLiteral { 

    let rows: Int 
    let columns: Int 
    var grid: [T] 

    public init(rows: Int, columns: Int, repeatedValue: T) { 
     self.rows = rows 
     self.columns = columns 

     self.grid = [T](repeating: repeatedValue, count: rows * columns) 
    } 
} 

extension Matrix: Sequence { 
    public func makeIterator() -> AnyIterator<ArraySlice<T>> { 
     let endIndex = rows * columns 
     var nextRowStartIndex = 0 

     return AnyIterator { 
      if nextRowStartIndex == endIndex { 
       return nil 
      } 

      let currentRowStartIndex = nextRowStartIndex 
      nextRowStartIndex += self.columns 

      return self.grid[currentRowStartIndex..<nextRowStartIndex] 
     } 
    } 
} 

這編譯以及帶斯威夫特3和4

+0

我看到運行。像魅力一樣工作......謝謝。 – dmr07