Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

swift2

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
}
like image 679
Marcelo Avatar asked Jan 02 '16 21:01

Marcelo


People also ask

What does if let do in Swift?

The “if let” allows us to unwrap optional values safely only when there is a value, and if not, the code block will not run. Simply put, its focus is on the “true” condition when a value exists.


1 Answers

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
   }
like image 179
mn1 Avatar answered Oct 13 '22 23:10

mn1