-2

I have the following playground code :

typealias ChessItemPosition = (alpha:Character, num:Int)
typealias Chessman = Dictionary<String,ChessItemPosition?>

var chessmans : Chessman = [:]
chessmans["White king"] = (alpha : "e", num : 2)
chessmans["Black king"] = (alpha : "e", num : 6)
chessmans["Black queen"] = nil

var itemPosition = chessmans["Black queen"]

if let chessItemPosition = itemPosition {
    print("Current position is : \(chessItemPosition!.alpha)\(chessItemPosition!.num)")
} else {
    print("Black queen is dead")
}

Why do I need to use !. syntax to access the tuple content? When I have

var markCount : Int? = 8

if let markCount_ = markCount {
    print("\(markCount_)")
}

and no ! is required here. What am I missing here?

Dmitry
  • 1,912
  • 2
  • 18
  • 29
  • 1
    Does this answer your question? [How to unwrap double optionals?](https://stackoverflow.com/questions/33049246/how-to-unwrap-double-optionals) – imike Dec 13 '20 at 22:48
  • @imike, thanks a lot for your hint - indeed I have a double optional in this case. I'll post an answer right now – Dmitry Dec 13 '20 at 22:54

1 Answers1

-1

The root cause is that I have a double optional here. It could be unwrapped like this :

typealias ChessItemPosition = (alpha:Character, num:Int)
typealias Chessman = Dictionary<String,ChessItemPosition?>

var chessmans : Chessman = [:]
chessmans["White king"] = (alpha : "e", num : 2)
chessmans["Black king"] = (alpha : "e", num : 6)
chessmans["Black queen"] = nil

var itemPosition = chessmans["Black queen"]

if let chessItemPosition = itemPosition, let chessItemPosition_ = chessItemPosition {
    print("Current position is : \(chessItemPosition_.alpha)\(chessItemPosition_.num)")
} else {
    print("Black queen is dead")
}
Dmitry
  • 1,912
  • 2
  • 18
  • 29