Harold Harold - 4 months ago 9
Swift Question

Swift: case foo (let bar): without a type or assignment?

In Swift, I understand that "let" defines a constant. No problem. So "let foo = 42" and "let foo: Int" make sense. But I see several instances where simply "let foo" is written without assignment or type specification. For example "case bar (let foo): ..."

What exactly happens when "let foo" by itself is in such code?

Answer

This notation is used to bind an associated value of an enumeration.

Take this for example:

let anOptionalInt: Int? = 15

switch (anOptionalInt) {
case .Some(let wrappedValue):
    print(wrappedValue)

case .None:
    print("the optional is nil")
}

This works because Optional is an enumeration. The first expression can be written as:

let anOptionalInt: Optional<Int> = Optional.Some(15)

There are two cases: .Some and .None. In the .Some case, there's an associated value, called Wrapped, whereas the .None case has no associated value.

In fact, Optional.None is the same as nil.