Marcelo
Marcelo

Reputation: 1206

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

This is just an example to illustrate what I am trying to achieve.

I want to check if an optional contains a value and if it is greater than 0. I currently have it this way:

if let value = Double(textFieldText) {
  if value > 0 {
    return true
  }
}

Is there any way to achieve this in a single line? Something like:

if let value = Double(textFieldText) && value > 0{
  return true
}

Upvotes: 14

Views: 2508

Answers (5)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52213

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.

Upvotes: 9

Abhishek Kumar
Abhishek Kumar

Reputation: 324

Try this.

if let value = textFieldText as? Double where value > 0 {
  return true
}

Upvotes: 0

mn1
mn1

Reputation: 509

One more way you can do the same thing and that would steer you away from ugly if let nesting.

   func hello(values:String) -> Bool {
      guard let value = Double(values) where value > 0 else {
         return false
      }     
      return true
   }

Upvotes: 2

Luca Angeletti
Luca Angeletti

Reputation: 59536

Solution in 1 line

I think the simplest way to write your logic is this

return Double(textFieldText) > 0

Test

func foo(textFieldText:String) -> Bool {
    return Double(textFieldText) > 0
}

foo("1") // true
foo("-1") // false
foo("a") // false
foo("0") // false
foo("123a") // false

Why does this work?

When 2 values are compared in Swift and (exactly) one of them is nil, then nil is always less than the other value.

So every time the initialiser of Double does fail, like here

return Double("a") > 0

the expression becomes

return nil > 0

which is false.

The only way the expression does return true is when the input string is parsed as a Double value which is actually greater then 0. Which is exactly the logic you where looking for :)

Upvotes: 6

Doug Richardson
Doug Richardson

Reputation: 10821

With a where clause:

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

Or simply:

if Double(textFieldText) > 0 {
    return true
}

Upvotes: 4

Related Questions