Boon
Boon

Reputation: 41500

Why is an optional array not enumerable in Swift?

Why is an optional array not enumerable in Swift? What's the best way to make it work?

e.g.

var objs:String[]?

// Won't work
for obj in objs {

}

Upvotes: 2

Views: 1457

Answers (2)

Wanbok Choi
Wanbok Choi

Reputation: 5452

=====Swift 2.1=====

objs?.forEach {
    print($0) // $0 is obj
}

the same as

objs?.forEach { obj in
    // Do something with `obj`
}

=====Swift 1.2=====

If you want to enumerate objs that is still be [String]?,

Try it

for i in 0 ..< (objs?.count ?? 0) {
    let obj = objs?[i]
}

Upvotes: 3

drewag
drewag

Reputation: 94733

You first need to "unwrap" the optional, or in other words, validate if it is nil or not:

if let actualObjs = objs {
    for obj in actualObjs {
    }
}

actualObjs becomes type: String[] and the block is run with it if objs is not nil. If objs is nil, the block will just be skipped. (For more information on this, read Apple's Documentation)

If you are positive that objs is not nil, you can also just use the force unwrap operator (!):

for obj in objs! {
}

If objs is nil in this case, it will throw a runtime error and the whole program will stop.

Note: The practical reason you need to unwrap the optional, is that an Optional is its own type in Swift:

enum Optional<T>

So when you try to interact with the Optional directly, you are really interacting with an enum. That enum just happens to store the real value within it. (hence the name "unwrap")

Upvotes: 7

Related Questions