Swift: How to use for-in loop with an optional?

Boon picture Boon · Sep 20, 2015 · Viewed 19.3k times · Source

What's the proper way to use for-in loop with an optional?

Right now I always perform an optional binding before looping it. Are there other idioms?

let optionalInt:[Int]? = [1, 2, 3]

if let optionalInt = optionalInt {
  for i in optionalInt {
    print(i)
  }
}

Answer

Richard Topchii picture Richard Topchii · Aug 1, 2016

If set of operations to be applied to all elements of the array, it is possible to replace for-loop with forEach{} closure and use optional chaining:

var arr: [Int]? = [1, 2, 3]
arr?.forEach{print($0)}