meaning of this code: return self.desk[number]![alpha]

45 Views Asked by At

please help me understand this part of the code. Why is ! located between two brackets []![] in this expression: self.desk[number]![alpha]?

class GameDesk {
    var desk : [Int: [String: Chessman]] = [:]

    init() {
        for i in 1...8 {
            desk[i] = [:]
        }
    }

    subscript(alpha: String, number: Int) -> Chessman? {
        get {
            return self.desk[number]![alpha]
        }
        set {
            if let chessman = newValue {
                self.setChessman(chess: chessman, coordinates: (alpha, number))
            } else {
                self.desk[number]![alpha] = nil
            }
        }
    }

    func setChessman(chess: Chessman, coordinates: (String, Int)){
        let rowRange = 1...8
        let colRange = "A"..."Z"
        if(rowRange.contains(coordinates.1) && colRange.contains(coordinates.0)) {
            self.desk[coordinates.1]![coordinates.0] = chess
            chess.setCoordinates(char: coordinates.0, num: coordinates.1)
        } else {
            print("Coordinates out of range")
        }
    }
}
1

There are 1 best solutions below

1
Geoff Hackworth On

desk is a dictionary with a key of Int and a value which is another dictionary that itself has a key of String and a value of Chessman. The subscript function implements setting or getting a piece by the row number and column string. A lookup in a dictionary returns an optional value (the key might not exist) but this code is (somewhat dangerously) assuming that it will never be called with an invalid number and is force unwrapping the lookup with the !. That makes the result non-optional and another dictionary lookup is performed to find the chess piece at the alpha. That can also be optional which is why the method returns an optional. This also means the code could have used ? as @vadian said in a comment.

That answers your question, but it’s worth mentioning that nested dictionaries is not a very good way to implement a chess board. A two dimensional array would be simpler and more efficient. But that’s a whole separate other question…