Swift bit #3 — Unwrap optional values using for in loop
• Rizwan Ahmed A • Swift fundamentals • swift, for loops, for in loops, unwrap, optionals
One of the most widely used features in Swift are the optionals. Optionals are types that can hold either a value or a nil value i.e nil.
Consider that there is an array of optional values. Usually, we use if let or guard statement to unwrap the optionals.
The above code is okay, nothing wrong with it, but we should try to use the power of Swift whenever we can.
We can unwrap the array of optionals using case let directly in the for in loop.
Here is how you do it,
Neat isn’t it? The number of lines of code is reduced, and the code looks more readable.
Note — There are also other techniques like using compactMap to unwrap optionals, I will be covering about them in upcoming articles. Follow me on Twitter. Have any queries? Feel free to DM me.
Like our articles? Support us!