Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Optional Patterns

Tags:

swift

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)
}
like image 625
Boon Avatar asked Jul 16 '15 12:07

Boon


People also ask

What is an optional function Swift?

Optional is the mechanism in Swift to indicate the possible absence of a value or a reference to an object.

Can any be optional Swift?

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.

How are optional implemented in Swift?

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.

Is optional enum in Swift?

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.


1 Answers

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

like image 138
DevAndArtist Avatar answered Sep 22 '22 21:09

DevAndArtist