Swift if statement - multiple conditions separated by commas?
Yes when you write
if let a = optA, let b = optB, let c = optC {
}
Swift does execute the body of the IF
only if all the optional bindings are properly completed.
More
Another feature of this technique: the assignments are done in order.
So only if a value is properly assigned to a
, Swift tries to assign a value to b
. And so on.
This allows you to use the previous defined variable/constant like this
if let a = optA, let b = a.optB {
}
In this case (in second assignment) we are safely using a
because we know that if that code is executed, then a
has been populated with a valid value.
Separating multiple if conditions with commas in Swift
Actually the result is not the same. Say that you have 2 statements in an if and && between them. If in the first one you create a let using optional binding, you won't be able to see it in the second statement. Instead, using a comma, you will.
Comma example:
if let cell = tableView.cellForRow(at: IndexPath(row: n, section: 0)), cell.isSelected {
//Everything ok
}
&& Example:
if let cell = tableView.cellForRow(at: IndexPath(row: n, section: 0)) && cell.isSelected {
//ERROR: Use of unresolved identifier 'cell'
}
Hope this helps.
Using multiple let-as within a if-statement in Swift
Update for Swift 3:
The following will work in Swift 3:
if let latitudeDouble = latitude as? Double, let longitudeDouble = longitude as? Double {
// latitudeDouble and longitudeDouble are non-optional in here
}
Just be sure to remember that if one of the attempted optional bindings fail, the code inside the if-let
block won't be executed.
Note: the clauses don't all have to be 'let' clauses, you can have any series of boolean checks separated by commas.
For example:
if let latitudeDouble = latitude as? Double, importantThing == true {
// latitudeDouble is non-optional in here and importantThing is true
}
Swift 1.2:
Apple may have read your question, because your hoped-for code compiles properly in Swift 1.2 (in beta today):
if let latitudeDouble = latitude as? Double, longitudeDouble = longitude as? Double {
// do stuff here
}
Swift 1.1 and earlier:
Here's the good news - you can totally do this. A switch statement on a tuple of your two values can use pattern-matching to cast both of them to Double
at the same time:
var latitude: Any! = imageDictionary["latitude"]
var longitude: Any! = imageDictionary["longitude"]
switch (latitude, longitude) {
case let (lat as Double, long as Double):
println("lat: \(lat), long: \(long)")
default:
println("Couldn't understand latitude or longitude as Double")
}
Update: This version of the code now works properly.
If let - Multiple conditions
You can add multiple conditions, but only if you use AND conditions.
If you use an OR
, you have no idea which of your value was properly set and thus cannot access properly the variables.
With an AND
test, you are sure that both variable were properly created, so you know with certainty their type.
You have to write the tests separated with a comma separator :
if let u = custom["u"],
let url = custom["URL"] {
// Do something here
}
Also, you can add some conditions directly after your if let
block , using the where
keyword :
if let u = custom["u"] where u == "testValue",
let url = custom["URL"] {
// Do something here
}
Guard statement with two conditions in Swift
You are using too many pointless parentheses, basically don't use parentheses in if
and guard
statements in simple expressions.
The error occurs because the compiler treats the enclosing parentheses as tuple ((Bool, Bool)
), that's what the error message says.
guard mode != "mapme" else {
guard !(annotation is MKUserLocation) else { // here the parentheses are useful but the `!` must be outside of the expression
guard mode != "mapme", !(annotation is MKUserLocation) else {
Multiple conditions in guard statement in Swift
Check this code
func demo(){
var str = [String: String]()
str["status"] = "blue"
str["asd"] = nil
guard let var2 = str["asd"], let var1 = str["status"]
else
{
print("asdsfddffgdfgdfga")
return
}
print("asdasdasd")
}
Guard will check one by one condition. If the first is true then it will check the next. Otherwise, it will execute the else part.
Are && and , the same in Swift?
They can be used in similar situations but that does not mean they are exactly the same.
Consider:
if (a && b) || c
you cannot write
if (a, b) || c
even a && b || c
is different from a, b || c
.
if a, b
is something like
if a {
if b {
...
}
}
Both expressions have to be evaluated to true
but they are still two separate expressions. We shouldn't imagine &&
there.
Why do we need the ,
operator?
The operator is needed to combine optional binding with boolean conditions, e.g.
if let a = a, a.isValid() {
becuase &&
wouldn't help us in such situations.
if (variable assignment) syntax query (Swift)
The let a = b
syntax used in an if statement is called optional binding. You can read more about it here. Essentially, if b
is nil, the condition is treated as "false". If b
is not nil, the condition is treated as "true", and a non optional constant a
will now have the value that b
has, and you can use it inside the if block.
Swift if statements also allow you to specify multiple conditions. All of them has to be "true" for the if block to be executed. These conditions doesn't have to be boolean expressions. They could be any of the following:
- Boolean expressions
- Optional Binding
#available
checkcase
pattern matching
If you have two boolean expressions and you want to run some code if both of them are true, you could use &&
to join them together, but if you have 2 optionals that you want to bind, or one boolean expression and one optional binding, or any combination of the above, you'd need to use a comma to separate the conditions.
Related Topics
How to Do Transforms on a Calayer
How to Integrate Nsurlconnection with Uiprogressview
"Could Not Find Any Information for Class Named Viewcontroller"
Should I Git Ignore Xcodeproject/Project.Pbxproj File
Generating an Unsigned IPA iOS Application
Swift - How to Get Last Taken 3 Photos from Photo Library
Behavior Differences Between Performblock: and Performblockandwait:
Error Appstore Connect:Missing Purpose String in Info.Plist File
Uipopovercontroller Dealloc Reached While Popover Is Still Visible
How to Set an Title of the Currently Playing Audio in iPhone Lock Screen
Nsstring Containsstring Crashes
Swift - Uiimagepickercontroller - How to Use It
iOS 13 - How to Login in In-App Purchase Sandbox Account
Libmobilegestalt Mobilegestaltsupport.M:153 Mobilegestalt.C:550 Xcode Console