coalesce()

The coalesce() function returns the first non-nil or assigned nullable value from its list of parameters, or nil/null if none of them is assigned. It supports both reference types and nullable value types, and a non-nullable value can be used as the last value in the parameter list as well.

Syntax:

method coalesce(expr1; expr2[; expr3 ...]): Value;
Value coalesce(expr1, expr2[, expr3 ...]);
func coalesce(_ expr1, _ expr2[, _ expr3 ...]) -> Value
Value coalesce(expr1, expr2[, expr3 ...]);

The resulting type, referred to as Value above, is the lowest common base type that all expressions have in common, with Object being the last fallback. When used with nullable value types, the resulting type will be nullable as well, unless the last parameter is a non-nullable value type, in which case it will return that type.

coalesce() only evaluates the passed expressions until a non-nil expression is found.

Example

Consider the following code:

var n1, n2: nullable Integer;
var s: string;

var r1 := coalesce(n1, n2);      // nullable integer
var r2 := coalesce(n1, 15);      // integer
var r3 := coalesce(n1, s);       // Object
var r4 := coalesce(s, 'test');   // String
int? n1, n2;
string s;

int? r1 = coalesce(n1, n2);      // nullable integer
int r2 = coalesce(n1, 15);       // integer
object r3 = coalesce(n1, s);     // Object
string r4 = coalesce(s, 'test'); // String
let n1, n2: Int?
let s: String?

let r1 = coalesce(n1, n2)        // nullable integer
let r2 = coalesce(n1, 15)        // integer
let r3 = coalesce(n1, s)         // Object
let r4 = coalesce(s, 'test')     // String
int? n1, n2;
String s;

int? r1 = coalesce(n1, n2);      // nullable integer
int r2 = coalesce(n1, 15);       // integer
Object r3 = coalesce(n1, s);     // Object
String r4 = coalesce(s, 'test'); // String