invert property
Map<V, K>
get
invert
Swaps keys and values (values must be unique)
Example:
final map = {'a': 1, 'b': 2, 'c': 3};
final swapped = map.swap();
print(swapped); // Output: {1: 'a', 2: 'b', 3: 'c'}
// Throws [ArgumentError] if values are not unique.
try {
final map = {'a': 1, 'b': 2, 'c': 3, 'd': 3};
final swapped = map.swap(); // Throws ArgumentError
} catch (e, stacktrace) {
print(stacktrace); // Output: 'SExtensionsError: Values must be unique, some values are duplicated.'
}
Implementation
Map<V, K> get invert {
if (values.toSet().length != values.length) {
throw ArgumentError(
'SExtensionsError: Values must be unique, some values are duplicated.',
);
}
return Map<V, K>.fromEntries(entries.map((e) => MapEntry(e.value, e.key)));
}