Optional chaining: some interesting syntax I ran across today

  1. The optional chaining I’m familiar with is of the form:

    someObj.property?.text = “hello”

Today, I saw syntax like this:

d["a"]?()

It certainly looks like optional chaining, but there’s no . in there. What’s going on is that a dictionary lookup, like d["a"], can return nil, so the ? is used to stop the statement from executing any further if the key doesn’t exist in the dictionary (rather than crashing). Then you can deduce that the value associated with "a" in the dictionary must be a function/closure/callable, and the () serves to immediately execute it. Here is an example:

let d = [    
    "a": { print("Hello") },
    "b": { print("World") },
]

d["a"]?()

--output:--
Hello
  1. As the docs explain, you can define an enum with associated values:

    enum BarCodes {
    case type1(Int, Int, String)
    case type2(Int)
    }

    let barcode = BarCodes.type1(3, 3, “hello”)

    switch barcode {
    case let .type1(x, y, z): //let applies to x, y, and z
    print(x, y, z) //=>3 3 "hello"
    case .type2(let x):
    print(x)
    }

But, what is undocumented is that you can name the associated values:

enum BarCodes {
    case type1(
        companyCode: Int,   //Name and type
        productCode: Int,
        productName: String
    )
    case type2(productCode: Int)
}

let barcode = BarCodes.type1(
    companyCode: 10,
    productCode: 2,
    productName: "soap"
)

switch barcode {
    case let .type1(x, y, z):  
        print(x, y, z)   //=> 10 2 "soap"
    case .type2(let x):
        print(x)
}