Boon
Boon

Reputation: 41500

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

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)
  }
}

Upvotes: 56

Views: 32682

Answers (5)

Peter Lapisu
Peter Lapisu

Reputation: 20995

the cleanest solution is sometimes the most basic one

if let a = myOptionalArray {
    for i in a {
        
    }
}

so i would suggest, keep your approach

the approaches above only insert an empty option, or the forEach creates a block just because if let a = optional { isn't sexi enough

Upvotes: 5

cloudcal
cloudcal

Reputation: 505

I'm two years late but I think this is the best way.

func maybe<T>(risk: T?, backup: T) -> T {
  return risk.maybe(backup)
}

and

extension Optional {
   func maybe(_ backup: Wrapped) -> Wrapped {
     switch self {
     case let .some(val):
        return val
     case .none:
        return backup
     }
   }
}

and now

for i in optionalInt.maybe([]) {
    print(i)
}

Upvotes: 0

Richard Topchii
Richard Topchii

Reputation: 8185

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)}

Upvotes: 54

luizParreira
luizParreira

Reputation: 1107

I don't think there's a proper way. There are many different ways, it really comes down to what you prefer, Swift is full of features that can make your program look really nice as per your choosing.

Here are some ways I could think of:

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

for i in optionalInt! { print(i) }

for i in optionalInt ?? [] { print(i) }

for i in optionalInt as [Int]! {  print(i) }

Upvotes: 24

Arsen
Arsen

Reputation: 10951

You can write this one:

let optionalInt:[Int]? = [1, 2, 3]
for i in optionalInt ?? [Int]() {
    print(i)
}

But I'd recommend you avoid using optional value, for instance you can write like this:

var values = [Int]()
// now you may set or may not set 
for i in values {
    print(i)
}

Or if you want to use optional value and this code calls in a function can use guard:

guard let values = optionalInt else { return }
for i in values {
    print(i)
}

Upvotes: 10

Related Questions