update

Calls create if key doesn't exist in the associative array, otherwise calls update. create returns a corresponding value for key. update accepts a key parameter. If it returns a value, the value is set for key.

void
update
(
K
V
C
U
)
(
ref V[K] aa
,
K key
,
scope C create
,
scope U update
)
if (
is(typeof(create()) : V) &&
(
is(typeof(update(aa[K.init])) : V) ||
is(typeof(update(aa[K.init])) == void)
)
)

Parameters

aa V[K]

The associative array.

key K

The key.

create C

The callable to create a value for key. Must return V.

update U

The callable to call if key exists. Takes a K argument, returns a V or void.

Examples

int[string] aa;

// create
aa.update("key",
    () => 1,
    (int) {} // not executed
    );
assert(aa["key"] == 1);

// update value by ref
aa.update("key",
    () => 0, // not executed
    (ref int v) {
        v += 1;
    });
assert(aa["key"] == 2);

// update from return value
aa.update("key",
    () => 0, // not executed
    (int v) => v * 2
    );
assert(aa["key"] == 4);

// 'update' without changing value
aa.update("key",
    () => 0, // not executed
    (int) {
        // do something else
    });
assert(aa["key"] == 4);

Meta