Key-Path Expression

let interestingNumbers = ["prime": [2, 3, 5, 7, 11, 13, 15],
                          "triangular": [1, 3, 6, 10, 15, 21, 28],
                          "hexagonal": [1, 6, 15, 28, 45, 66, 91]]

print(interestingNumbers[keyPath: \[String: [Int]].["prime"]![0]]) // right
print(interestingNumbers[keyPath: \[String: [Int]].["prime"]!.[0]]) 
// error, Under what circumstances, no dot operator ( after the exclamation point )?

interestingNumbers["prime"]![0] // correct
interestingNumbers["prime"]!.[0] // error

The rule is that you chain subscripts without a dot. [key]?[key]![key] etc.

let greetings = ["hello", "hola", "bonjour", "안녕"]
let myGreeting = greetings[keyPath: \[String].[1]]

How does this explain?

You have to add a dot after the root type. Compare it with this example:

let greetings = [["hello"], ["hola"], ["bonjour"], ["안녕"]]
let myGreeting = greetings[keyPath: \[[String]].[1][0]]
1 Like