下面是一个教程中的类,我很努力地理解其中的语法。Swift:通过示例进行关闭和澄清
import Foundation
class Board {
private var cells: [BoardCellState]
let boardSize = 8
init() {
cells = Array(count: boardSize * boardSize,
repeatedValue: BoardCellState.Empty)
}
subscript(location: BoardLocation) -> BoardCellState {
get {
assert(isWithinBounds(location), "row or column index out of bounds")
return cells[location.row * boardSize + location.column]
}
set {
assert(isWithinBounds(location), "row or column index out of bounds")
cells[location.row * boardSize + location.column] = newValue
}
}
subscript(row: Int, column: Int) -> BoardCellState {
get {
return self[BoardLocation(row: row, column: column)]
}
set {
self[BoardLocation(row: row, column: column)] = newValue
}
}
func isWithinBounds(location: BoardLocation) -> Bool {
return location.row >= 0 && location.row < boardSize &&
location.column >= 0 && location.column < boardSize
}
func cellVisitor(fn: (BoardLocation) ->()) {
for column in 0..<boardSize {
for row in 0..<boardSize {
let location = BoardLocation(row: row, column: column)
fn(location)
}
}
}
func clearBoard() {
cellVisitor { self[$0] = .Empty }
}
}
我需要帮助的最后两个功能:
func cellVisitor(fn: (BoardLocation) ->()) {
for column in 0..<boardSize {
for row in 0..<boardSize {
let location = BoardLocation(row: row, column: column)
fn(location)
}
}
}
func clearBoard() {
cellVisitor { self[$0] = .Empty }
}
我的理解:
cellVisitor
发生在它接受的BoardLocation
实例的功能,并返回一个void
接下来,我们terate
column
通过0
到8
的值,并且我们通过对row
的迭代通过0
到8
将它嵌套。这意味着组合循环,我们将调用函数
fn(location)
64次。
这是我迷路的地方。
问题1:为什么我们叫中传递函数fn(location)
和location
64次传球的时候有什么回来?
问题2:我真的不明白cellVisitor { self [$0] = .Empty }
的目的。 .Empty
是来自struct
的值0
。
问题3:速记$0
的意思是只设置.Empty
的第一个元素吗?
这个问题太宽泛,无法标记为任何单个问题的重复... – nhgrif