Swift optional pattern allows you to use case let like this:
var arrayOfOptional: [Int?] = [1, 2, nil, 4]
for case let number? in arrayOfOptional {
print("\(number)")
}
What confuses me is the let number? syntax. In optional binding, the unwrapped version does not have ?, but in case let, it does. How do you interpret this construct for it to make sense for you that number is unwrapped?
Functionally, what's the difference between the two below:
if let x = someOptional {
print(x)
}
versus
if case let x? = someOptional {
print(x)
}
Optional is the mechanism in Swift to indicate the possible absence of a value or a reference to an object.
Any data type can be optional in Swift: An integer might be 0, -1, 500, or any other range of numbers. An optional integer might be all the regular integer values, but also might be nil – it might not exist.
Optionals: Swift introduced optionals that handle the absence of a value, simply by declaring if there is a value or not. An optional is a type on it's own! enum: An enumerated type is a data type consisting a set of members of the type.
Optional is actually an enum, defined in relation to a generic type Wrapped. It has two cases: . none to represent the absence of a value, and . some to represent the presence of a value, which is stored as its associated value of type Wrapped.
I just tested your first code, never used for pattern matching before but here is what I assume:
var arrayOfOptional: [Int?] = [1, 2, nil, 4]
for case let number in arrayOfOptional {
print("\(number)")
}
// will return 3 optional ints and a nil
for case let number? in arrayOfOptional {
print("\(number)")
}
// will return only any values that could be unwrapped
I assume that this is a pattern which unwraps any optional value under the hood and only proceed if it could be unwrapped and will.
if case let x? = someOptional {
print(x)
}
case let
is used for pattern matching like switch x { case let ... }
. In your example it will also try to unwrap an optional value. If it's a nil it will fail
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With