This week, I learnt two things about Swift that I’d never come across before. Both involve loops.
The first, via Erica Sadun: you can use case let
in a for
loop to conditionally bind optionals or cast items. Here’s the optional binding example from Erica’s post:
let items: [String?] = [nil, nil, "Hello", nil, "World"] for case let item? in items { print(item) }
Check out the full post, 3 simple for-in iteration tricks for some other neat tricks.
Secondly, from this post at KrakenDev: you can label loops in Swift! Here’s an example:
sectionLoop: for section in sections { rowLoop: for row in rows { if row.isMagical { break sectionLoop } } }
Who knew?! There are a bunch more useful tips in the full post, Hipster Swift, including descriptions of what @noescape
and @autoclosure
actually do.