×

# 【译】Swift算法俱乐部-二维数组

Swift算法俱乐部

Swift Algorithm Clubraywenderlich.com网站出品的用Swift实现算法和数据结构的开源项目，目前在GitHub上有18000+⭐️，我初略统计了一下，大概有一百左右个的算法和数据结构，基本上常见的都包含了，是iOSer学习算法和数据结构不错的资源。
🐙andyRon/swift-algorithm-club-cn是我对Swift Algorithm Club，边学习边翻译的项目。由于能力有限，如发现错误或翻译不妥，请指正，欢迎pull request。也欢迎有兴趣、有时间的小伙伴一起参与翻译和学习🤓。当然也欢迎加⭐️，🤩🤩🤩🤨🤪。

``````int cookies[9][7];
``````

``````myCookie = cookies[3][6];
``````

``````var cookies = [[Int]]()
for _ in 1...9 {
var row = [Int]()
for _ in 1...7 {
row.append(0)
}
}
``````

``````let myCookie = cookies[3][6]
``````

``````var cookies = [[Int]](repeating: [Int](repeating: 0, count: 7), count: 9)
``````

``````func dim<T>(_ count: Int, _ value: T) -> [T] {
return [T](repeating: value, count: count)
}
``````

``````var cookies = dim(9, dim(7, 0))
``````

Swift推断数组的数据类型必须是`Int`，因为您指定了`0`作为数组元素的默认值。 要使用字符串数组，您可以编写：

``````var cookies = dim(9, dim(7, "yum"))
``````

`dim()`函数可以更容易地创建更多维度的数组：

``````var threeDimensions = dim(2, dim(3, dim(4, 0)))
``````

``````public struct Array2D<T> {
public let columns: Int
public let rows: Int
fileprivate var array: [T]

public init(columns: Int, rows: Int, initialValue: T) {
self.columns = columns
self.rows = rows
array = .init(repeating: initialValue, count: rows*columns)
}

public subscript(column: Int, row: Int) -> T {
get {
precondition(column < columns, "Column \(column) Index is out of range. Array<T>(columns: \(columns), rows:\(rows))")
precondition(row < rows, "Row \(row) Index is out of range. Array<T>(columns: \(columns), rows:\(rows))")
return array[row*columns + column]
}
set {
precondition(column < columns, "Column \(column) Index is out of range. Array<T>(columns: \(columns), rows:\(rows))")
precondition(row < rows, "Row \(row) Index is out of range. Array<T>(columns: \(columns), rows:\(rows))")
array[row*columns + column] = newValue
}
}
}
``````

`Array2D`是一个泛型，因此能够支持所有类型对象，而不是只能是数字

``````var cookies = Array2D(columns: 9, rows: 7, initialValue: 0)
``````

``````let myCookie = cookies[column, row]
``````

``````cookies[column, row] = newCookie
``````

Swift算法俱乐部
Swift算法俱乐部
3.0万字 · 944阅读 · 19人关注