Swift bit #3 — Unwrap optional values using for in loop
source link: https://ohmyswift.com/blog/2019/08/03/swift-bit-3-unwrap-optional-values-using-for-in-loop/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Swift bit #3 — Unwrap optional values using for in loop
Aug 3, 2019 • Rizwan • 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.
//An array of optionals.
let cars = ["Ford","Lamborghini",nil,"McLaren","Aston Martin",nil]
for car in cars {
if let carObject = car{
print(carObject)
}
}
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,
//An array of optionals.
let cars = ["Ford","Lamborghini",nil,"McLaren","Aston Martin",nil]
for case let car? in cars {
print(car)
}
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!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK