Using "If Let" with Logical "Or" Operator

Using if let with logical or operator

Try to use ?? operator:

if let amount = datasource?.incrementForCount?(count) ?? datasource?.fixedIncrement 
{
count += amount
}

is it possible to combine the 2 if let statements into a single ORed one ?

It is possible to have several let statements like

if let a = optionalA, b = optionalB { ... }

And all of them should return non-nil value to pass.

But if you also want to use a logical condition it:

  1. Could be only the one
  2. Should be placed on the first place, before any let statements

Using the Swift if let with logical AND operator &&

As of Swift 1.2, this is now possible. The Swift 1.2 and Xcode 6.3 beta release notes state:

More powerful optional unwrapping with if let — The if let construct
can now unwrap multiple optionals at once, as well as include
intervening boolean conditions. This lets you express conditional
control flow without unnecessary nesting.

With the statement above, the syntax would then be:

if let tabBarController = window!.rootViewController as? UITabBarController where tabBarController.viewControllers.count > 0 {
println("do stuff")
}

This uses the where clause.

Another example, this time casting AnyObject to Int, unwrapping the optional, and checking that the unwrapped optional meets the condition:

if let w = width as? Int where w < 500
{
println("success!")
}

For those now using Swift 3, "where" has been replaced by a comma. The equivalent would therefore be:

if let w = width as? Int, w < 500
{
println("success!")
}

if let with OR condition

This would make no sense, how would you be able to tell whether value is an Int or a String when you only have one if statement? You can however do something like this:

let dictionary : [String : Any] = ["test" : "hi", "hello" : 4]


if let value = dictionary["test"] where value is Int || value is String {
print(value)
}

(Tested in Swift 2.0)

You can also do this if you need to do different things depending on the types:

if let value = dictionary["test"] {
if let value = value as? Int {
print("Integer!")
} else if let value = value as? String {
print("String!")
} else {
print("Something else")
}
}

Swift: Combine condition and if-let with logical or

The equivalent to your code example would be:

if text == "" || Int(text) ?? 2 < 2 {
print("valid")
// do your previous "something
} else {
print("invalid")
}

which yields

"" -> valid

"1" -> valid

"2" -> invalid

"abc" -> invalid

Multiple if let and OR condition in swift


if let value1 = profile.value1, value1 != “” {}
else if value2 = profile.value2, value2 != “” {}
else if value3 = profile.value3, value3 != “” {}

here , acts like &&

Pay attention:
For Swift 2 replace , with where

Use or logic with multiple if case statements

I would resort to some sort of isBar property on the enum itself, so that the "a or b" test remains readable:

enum MyEnum {
case foo, bar(_ prop: Int)

var isBar: Bool {
switch self {
case .bar: return true
default: return false
}
}
}

let var1 = MyEnum.foo
let var2 = MyEnum.bar(1)

let eitherIsBar = var1.isBar || var2.isBar

How do I mix boolean comparisons and 'if let' statements in a clean way?

If your enum implements PartialEq, this should also work:

fn is_mine(&self, row: i32, col: i32) -> bool {
self.bounds.is_in_bounds(row, col)
&& self.field[row as usize][col as usize] == MineCell::Mine
}

Using If-Let and checking the output in a single line

You can use where clause:

if let value = Double(textFieldText) where value > 0 {

Another option using nil coalescing operator:

if Double(textFieldText) ?? -Double.infinity > 0 {

Thanks to comments below which help me realize nil > 0 doesn't throw an error:

if Double(textFieldText) > 0 {

is by far the simplest option.



Related Topics



Leave a reply



Submit