Swift Error: 'Sequence' requires the types 'T' and 'ArraySlice' be equivalent

前端 未结 1 820
余生分开走
余生分开走 2021-01-18 11:54

I\'m trying to update a math library to be compatible with Swift 3, but I\'m running into an error:

\'Sequence\' requires the types \'T\' and \'ArraySlice<

相关标签:
1条回答
  • 2021-01-18 12:13

    Your code compiles fine as Swift 3.1 (Xcode 8.3.3). The error

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

    occurs when compiling as Swift 4 (Xcode 9, currently beta), because then the Sequence protocol already defines the

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

    which conflicts with your definition. You can either choose a different name for your type alias, or just remove it (and use T instead):

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

    This compiles and runs with both Swift 3 and 4.

    0 讨论(0)
提交回复
热议问题