2

pushIsActivated is an optional bool variable. I use this code to check it's value

if let pushOn = pushIsActivated {
    if pushOn {
        // Do some stuff...
    }
}

is it possible to do something like

if let pushOn = pushIsActivated, pushOn {
    // Do some stuff ...
}

Or

if let pushOn = pushIsActivated && pushOn {
    // Do some stuff ...
}
Key
  • 6,986
  • 1
  • 23
  • 15
user567
  • 3,712
  • 9
  • 47
  • 80

5 Answers5

2

Sure! Check this simple example:

var testBool: Bool?
    testBool = true
    if let unwrappedTestBool = testBool, unwrappedTestBool {
        print("Success")
    }
Artem Novichkov
  • 2,356
  • 2
  • 24
  • 34
2

Yes, it is!

var aVal: Bool?

aVal = true
if let aVal = aVal, aVal {
    print(aVal)
}
J. Koush
  • 1,028
  • 1
  • 11
  • 17
0

Yes, you can check both the values in a single if condition like this

if let pushOn = pushIsActivated, let pushOn1 = anotherCondition {
// Do some stuff ...
}
Rajat
  • 10,977
  • 3
  • 38
  • 55
0

The line should be:

if let pushOn = pushIsActivated where pushOn {

}
aramusss
  • 2,391
  • 20
  • 30
  • You''re using deprecated Swift 2 syntax, while the question gives an example with a newer Swift 3 syntax. – Cœur Nov 28 '16 at 16:42
  • 1
    I am using swift 2 and not 3, the syntax in the question was not working for me that's why I asked it. This syntax is working perfectly for me. – user567 Nov 30 '16 at 16:51
-2

I usually compare to true in these cases

if pushIsActive == true {
    // Run when pushIsActive is true
} else {
    // Run when pushIsActive is nil or false
}
Key
  • 6,986
  • 1
  • 23
  • 15
  • It would be nice to get comments on why this is being down voted. This will give the exact result at the accepted answer, but with less code. – Key Dec 01 '16 at 07:04