2

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 {

}

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

4 Comments

What's let actualObjs = objs doing? Can you explain?
@manojlds "if let" is a special syntax for unwrapping optionals (and some other things). There isn't much to be said other than it tests if the optional is nil. If it is not nil, it assigns the value to "actualObjs" as a normal (non-optional) value and runs the if block
@drewag - ah, ok thanks. Is there a documentation link explaining this? Wasn't able to find it.
@manojlds It is described here
3

=====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]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.