The Swift documentation at page 61 of the Swift manual hints to the possibility of using where
to join an optional binding with a regular condition. Yet when I do it I have a warning suggesting me to substitute the where
with a comma like in the following piece of code:
if let geocodingError = error as? NSError where geocodingError.code == 2
You use where in Swift to filter things, kinda like a conditional. In various places throughout Swift, the “where” clause provides a constraint and a clear indicator of the data or types you want to work with.
The “if let” allows us to unwrap optional values safely only when there is a value, and if not, the code block will not run. Simply put, its focus is on the “true” condition when a value exists.
In if let , the defined let variables are available within the scope of that if condition but not in else condition or even below that. In guard let , the defined let variables are not available in the else condition but after that, it's available throughout till the function ends or anything.
In swift, we use the let keyword to declare a constant variable, a constant is a variable that once declared, the value can not be changed.
In Swift 3 this syntax has changed.
What was
if let x = y, a = b where a == x {
Is now
if let x = y, let a = b, a == x {
The justification is that each sub-clause of the if ... {
is now an independent boolean test.
See the Xcode Release notes & the Swift Evolution proposal for more info about this change.
Example with two conditions
if let x = y, let a = b, a == x && !x.isEmpty {
In xcode 9
if let str = textField.text as String!, !str.isEmpty
{
params[key] = str
TextFieldHelper.setup(textField: textField)
}
else
{
TextFieldHelper.error(textField: textField)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With