gpt4 book ai didi

swift 错误 : 'Sequence' requires the types 'T' and 'ArraySlice' be equivalent

转载 作者:搜寻专家 更新时间:2023-10-30 23:08:11 26 4
gpt4 key购买 nike

我正在尝试更新数学库以与 Swift 3 兼容,但我遇到了一个错误:

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

Apple 关于 Sequence 的文档建议 makeIterator() 方法返回一个迭代器,它确实这样做了。迭代器似乎返回了 grid 中的一个元素变量,即变量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,当前测试版)时发生,因为那时Sequence 协议(protocol)已经定义了

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]
}
}
}

这可以在 Swift 3 和 4 上编译和运行。

关于 swift 错误 : 'Sequence' requires the types 'T' and 'ArraySlice<T>' be equivalent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45668497/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com