同类型约束 'Element' == 'Array<Element>' 是递归的

Same-type constraint 'Element' == 'Array<Element>' is recursive

我想为矩阵创建一个灵活的初始值设定项,让我使用默认元素定义行数和列数。如何为数组的数组创建扩展?当我尝试下面的方式时,

extension Array where Element == Array<SubElement> {

    init(rows: Int, columns: Int, emptyDefault: SubElement) {

        self = [] 
        // implementation
    }

}

我收到以下错误:

// Same-type constraint 'Element' == 'Array<Element>' is recursive

一个示例用法是

self = [[UIColor]](rows: 20, columns: 30, emptyDefault: .blue)
// This would create a matrix with 20 rows, each row having an array of 30 .blue

我希望能够做那样的事情。

它并不完美,这是我的临时解决方法:

extension Collection where Element: Collection {

}

如果您需要创建元素矩阵,您可以扩展 RangeReplaceableCollection 并将其元素也限制为 RangeReplaceableCollection。您需要将 Element.Element 类型的默认元素添加到您的初始化程序以填充您的集合:

extension RangeReplaceableCollection where Element: RangeReplaceableCollection { 
    init(rows: Int, columns: Int, element: Element.Element) { 
        self.init(repeating: .init(repeating: element, count: columns), count: rows) 
    }
}

用法:

let matrix: [[UIColor]] = .init(rows: 3, columns: 3, element: .blue)

Leo的回答很好。

但是更严格的解决方案看起来像这样,将约束移至初始值设定项:

extension Array {
  init<Element>(rows: Int, columns: Int, emptyDefault: Element) where Self.Element == [Element] {

  }
}