Marcelo Marcelo - 4 years ago 77
Swift Question

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

Answer Source

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 helps me realize nil > 0 doesn't throw an error:

if Double(textFieldText) > 0 {

is by far simplest option.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download