Swift TIL 4

Posted on 2020-06-25 13:21 +0100 in TIL • 1 min read

Some languages favour a "one way to do it" approach, some favour "there's more than one way to do it". I'm not sure I'm at a point where I have a feel for what Swift's approach is, but I'm getting the impression it's more the latter than the former.

If there was one thing that made me think that, it was when I found out that Swift's bool type has a toggle method.

var cool = false

print( cool )
cool = !cool
print( cool )
cool.toggle()
print( cool )

giving:

$ swift run
false
true
false

I can see a number of reasons why that's actually going to be handy -- the main one being when you want to throw around a toggling method -- but it still struck me as rather odd on first reading. I also think it's worth me making a personal note about it because foo.toggle() isn't going to stand out as much as foo = !foo when reading code. At least not for a short while.