2017-06-30 48 views
0

我讀過幾篇關於訪問結構成員內部結構成員的類似帖子,並嘗試了一些他們的解決方案。如果您覺得不然,請在投票前發表評論。Swift根據另一個結構變量設置結構變量var(試過初始化)

我有結構網格需要以便確定許多細胞在網格如何都活着訪問結構單元{風險狀態的構件的延伸。我的嘗試被註釋掉了。爲什麼我不能訪問cell.state

extension Grid { 
    var numLiving: Int { 
     return positions(rows: self.rows, cols: self.cols).reduce(0) { total, position in 
      // let myState = Cell.state() 
      // return myState.isAlive ? (total + 1) : (total) 
      // error: instance member 'state' cannot be used on type 'Cell' 
     } 
    } 
} 

細胞絕對有與狀態的枚舉的狀態成員:

struct Cell { 
    var position: (Int,Int) 
    var state: CellState 

    init(_ position: (Int,Int), _ state: CellState) { 
     self.position = (0,0) 
     self.state = .empty 
    } 
} 

enum CellState { 
    case alive 
    case empty 
    case born 
    case died 

    var isAlive: Bool { 
     switch self { 
     case .alive, .born: return true 
     case .empty, .died: return false 
     } 
    } 
} 

struct Grid { 
    var rows: Int = 10 
    var cols: Int = 10 
    var cells: [[Cell]] = [[Cell]]() 

    init(_ rows: Int, 
     _ cols: Int, 
     cellInitializer: (Int, Int) -> CellState = { _,_ in .empty }) { 
      self.rows 
      self.cols 
      self.cells = [[Cell]](repeatElement([Cell](repeatElement(Cell((0,0), .empty), count: cols)),count: rows)) 

     positions(rows: rows, cols: cols).forEach { row, col in 
      cells[row][col].position = (row, col) 
      cells[row][col].state = .empty 
} 

回答

1

您需要使用position訪問特定cellcells屬性,然後調用該cellstateisAlive

var numLiving: Int { 
    return positions(rows: self.rows, cols: self.cols).reduce(0) { total, position in 
     if cells[position.0][position.1].state.isAlive { 
      return total + 1 
     } else { 
      return total 
     } 
    } 
} 

這可能是更緊湊的書面使用三元運算符爲:

var numLiving: Int { 
    return positions(rows: self.rows, cols: self.cols).reduce(0) { total, position in 
     total + (cells[position.0][position.1].state.isAlive ? 1 : 0) 
    } 
} 
+0

謝謝!所以這基本上是在說「給我這個牢房,無論這個位置是什麼,並檢查這個狀態」? – HashRocketSyntax

+0

'positions'調用返回一個位置元組數組。通過每個位置減少循環,保持總計。 'position'是一個'(row,col)'元組,所以'position.0'是行,'position.1'是col。使用這些,你可以從'cells'的那個位置得到單元格,然後檢查它的狀態以決定是否需要添加到總數中。 – vacawama

2

那不是如何結構工作。您正嘗試訪問尚未創建的結構的實例變量。

你不得不這樣做

var cell = Cell(...) 

然後調用:

cell.state 

在網格擴展你可能會想訪問你已經爲你的遊戲創建了所有細胞然後從這些狀態中獲得狀態。

+0

謝謝。我一直在想如何創建所有! – HashRocketSyntax