# 在 Swift 结构体中使用 Mutating 函数的最佳时机

jwob6384 6年前

</div>

### 函数方式

`struct Position {      let coordinate: Coordinate      let state: State            enum State: Int {          case X, O, Empty      }  }     struct Board {            let positions: [Position]         // 需要添加一个函数来更新位置      // 从空棋盘到 X 或 O   }`
</div>

`struct Board {            let positionsMatrix: [[Position]]            init() {         // 初始化一个初始棋盘      }         // 函数式的实现方式      func boardWithNewPosition(position: Position) -> Board {          var positions = positionsMatrix          let row = position.coordinate.row.rawValue          let column = position.coordinate.column.rawValue          positions[row][column] = position          return Board(positionsMatrix: positions)      }  }`
</div>

`class BoardTests: XCTestCase {         func testBoardWithNewPosition() {          let board = Board()          let coordinate = Coordinate(row: .Middle, column: .Middle)                    let initialPosition = board[coordinate]          XCTAssertEqual(initialPosition.state, Position.State.Empty)                    let newPosition = Position(coordinate: coordinate, state: .X)          let newBoard = board.boardWithNewPosition(newPosition)          XCTAssertEqual(newBoard[coordinate], newPosition)      }  }`
</div>

### 使用 Mutating 关键字

`struct Counter {      let count: Int            init(count: Int = 0) {          self.count = count      }            // 需要一个方法来增加计数  }`
</div>

`struct Counter {      let count: Int            init(count: Int = 0) {          self.count = count      }            // 函数式的实现方式      func counterByIncrementing() -> Counter {          let newCount = count + 1          return Counter(count: newCount)      }  }`
</div>

`var counter = Counter()  counter = counter.counterByIncrementing()`
</div>

`struct Counter {      // 现在这个 count 改为变量了 :/      var count: Int            init(count: Int = 0) {          self.count = count      }            // 使用 mutating 关键字来实现修改 count       mutating func increment() {          count += 1      }  }`
</div>

`var counter = Counter()  counter.increment()`
</div>

`struct Counter {      // 将 setter 方法设为私有,       // 这样只有 increment 函数能够修改它!      private(set) var count: Int            init(count: Int = 0) {          self.count = count      }            // 使用 mutating 关键字来实现修改 count       mutating func increment() {          count += 1      }  }`
</div>

</div>