你的代碼編譯得很好,就像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
我看到運行。像魅力一樣工作......謝謝。 – dmr07