Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of where in if let assignment in Swift

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
like image 973
Fabrizio Bartolomucci Avatar asked Aug 04 '16 08:08

Fabrizio Bartolomucci


People also ask

What is where clause in Swift?

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.

What does if let do in Swift?

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.

When we use if let and when we use guard let?

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.

What is let _ in Swift?

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.


3 Answers

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.

like image 195
Grimxn Avatar answered Oct 19 '22 07:10

Grimxn


Example with two conditions

if let x = y, let a = b, a == x && !x.isEmpty {
like image 37
Alex Avatar answered Oct 19 '22 05:10

Alex


In xcode 9

if let str = textField.text as String!, !str.isEmpty
{
   params[key] = str
   TextFieldHelper.setup(textField: textField)
}
else
{ 
   TextFieldHelper.error(textField: textField)
}
like image 26
luhuiya Avatar answered Oct 19 '22 07:10

luhuiya