1

In Swift, there's a simple language feature to chain unwrapping and checking for non null like this:

if let data = functionReturningNullableNumber(), data != 0 { processNum(data) }
if let data = functionReturningNullableString(), data != "" { processStr(data) }

In Flutter, currently I have to do this:

var dataNum = functionReturningNullableNumber();
if (dataNum != null && dataNum != 0) { processNum(dataNum); }
var dataStr = functionReturningNullableString();
if (dataStr != null && dataStr != "") { processStr(dataStr); }

Is it possible to create something similar to the Swift above? Especially the part where I can assign a temporary variable name that will disappear outside of the if scope, so I can reuse the variable name.

Of course I can do this:

if (functionReturningNullableNumber() != null && functionReturningNullableNumber() != 0) { process(functionReturningNullableNumber()); }

But this isn't what I'm searching for.

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
Chen Li Yong
  • 5,459
  • 8
  • 58
  • 124
  • Note that for your example you can simply do `functionReturningNullableNumber() != 0`, not sure if the same is possible in flutter (but probably is) – Schottky Jun 26 '21 at 08:04
  • @Schottky I'm not sure you should. While it compiles, you'd actually have to run the function again inside the brackets to pass the argument to the `processNum` function. In OPs example he assigns the value to a variable `data` so he does not have to call the function again. – Uzaak Apr 19 '23 at 13:05

0 Answers0