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 assignments 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.
Swift and multiple conditions?
More specific, what does
let char = str.first, condition(char)
do?
Nothing. There is no such expression in your code.
What’s there is this:
guard let char = str.first, condition(char)
That guard
makes all the difference. The comma joins two conditions as by nesting, so we have, in effect (since guard
is a form of if
):
if let char = str.first
and
if condition(char)
You understand both of those well enough, surely? If not, the only remaining thing that might be unfamiliar to you is if let
, which is extremely fundamental to Swift and easy to learn about; it unwraps the Optional safely, avoiding the danger of crashing thru an attempt to unwrap nil.
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 {
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.
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.
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.
Related Topics
What's the Simplest Way to Convert from a Single Character String to an Ascii Value in Swift
Prevent Dismissal of Uialertcontroller
How to Create Local Scopes in Swift
Swiftui Iterating Through Dictionary With Foreach
Get Terminal Output After a Command Swift
Decrement Index in a Loop After Swift C-Style Loops Deprecated
What Is the Meaning of the '#' Mark in Swift Language
Convert String to Url (Why Is Resulting Variable Nil)
Swift Closure Async Order of Execution
== Overload for Custom Class Is Not Always Called
Why Convenience Keyword Is Even Needed in Swift
Swift - Sort Array of Objects With Multiple Criteria
Do Swift-Based Applications Work on Os X 10.9/Ios 7 and Lower
How to Get the Count of a Swift Enum