我正在尝试更新数学库以与
Swift 3兼容,但我遇到了一个错误:
‘序列’需要类型’T’和’ArraySlice< T>‘相当于
关于Sequence的Apple文档建议makeIterator()方法返回一个迭代器.似乎迭代器在网格变量中返回一个元素,它是变量T.我不太确定我在这里缺少什么.任何意见将是有益的.
public struct Matrix<T> where T: FloatingPoint,T: ExpressibleByFloatLiteral { public typealias Element = T let rows: Int let columns: Int var grid: [Element] public init(rows: Int,columns: Int,repeatedValue: Element) { self.rows = rows self.columns = columns self.grid = [Element](repeating: repeatedValue,count: rows * columns) } ... } extension Matrix: Sequence { // <-- getting error here public func makeIterator() -> AnyIterator<ArraySlice<Element>> { 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] } } }
解决方法
您的代码编译为Swift 3.1(Xcode 8.3.3).错误
'Sequence' requires the types 'T' and 'ArraySlice<T>' be equivalent
当编译为Swift 4(Xcode 9,目前为beta)时,会发生这种情况
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,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] } } }
这与Swift 3和4一起编译和运行.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。