Quick add-on templates

The optional Swift template allows you to use case let as follows:

var arrayOfOptional: [Int?] = [1, 2, nil, 4] for case let number? in arrayOfOptional { print("\(number)") } 

What does let number syntax bother me ? . In an optional binding, does the deployed version not have ? but if yes, then does. How do you interpret this construction so that it makes sense to you that the number is deployed?

Functionally, what is the difference between the two below:

 if let x = someOptional { print(x) } 

vs

 if case let x? = someOptional { print(x) } 
+6
source share
1 answer

I just checked your first code, which was never used for pattern matching, 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 guess this is a template that expands any optional value under the hood and only continues if it can be expanded and will be.

 if case let x? = someOptional { print(x) } 

case let used for pattern matching, for example, switch x { case let ... } . In your example, it will also try to expand the optional value. If it is zero, it will be

+1
source

All Articles