New Syntax of Optional Unwrapping in Swift 5.7 (WWDC 2022) — Most Popular Interview Question 😊
Apple also announced Swift 5.7 which will come along with the release of Xcode 14. Let’s check out new Swift 5.7’s new optional unwrapping syntax.
Optional Binding is a common way to find out whether a value in optional exist or not. see code snippets
Typical way of Optional Unwrapping !!!
var userName: String?if let userName = userName {
print("User name: \(userName)")
}
New Syntax:
Now, We can simply ignore the assignment after the if let
or guard let statement, and the Swift compiler will automatically unwrap the optional for us. Under the hood compiler create a non-optional value with the exact same variable name.
struct UserModel {
var userName: String?
var getUserName: String {
if let userName {
return userName
}
return "N/A"
}
}var getUserName: String {
guard let userName else {
return "N/A"
}
return userName
}
Unwrapping multiple Optionals!!!
struct UserModel {
var userName: String?
var userId: String?
var loginTime: String?
func printLoginDetails() {
guard let userName, let userId, let loginTime else {
print("Unable to find details")
} print("User name with :\(userName) having user Id: \(userId) logged in at : \(loginTime)")
}
}
Conclusion:
Optional binding extensively used in writing Swift code, this will make code more readable, removing duplicate variable. And obviously save time by reducing number of keystrokes 😊