subtract
and subtracting
both computes the difference of 2 sets, but subtract
is mutating, whereas subtracting
is not.
This means that x.subtract(y)
changes the set x
to the computed difference, whereas x.subtracting(y)
doesn't change x
at all, and instead returns the difference. On the other hand, subtract
returns nothing (Void
).
When you do
let different = setA.subtract(setB) // I GET HERE ()
print(different)
you see ()
being printed, because that is what the string representation of Void
looks like - an empty tuple.
This works
employees.subtract(neighbors)
print(employees)
because subtract
changes employee
.
This also works:
let different = setA.subtracting(setB)
print(different)
because the return value of subtracting
- the set difference - is assigned to different
. Note that this doesn't change setA
.
This doesn't work:
employees.subtracting(neighbors)
print(employees) // still shows the original employees
Because subtracting
doesn't change employees
, and you are ignoring its return value.
There are many other pairs of such mutating vs non-mutating methods, like
Set.formUnion
vs Set.union
String.append
vs String.appending
Related post
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…