KelticKoder
KelticKoder

Reputation: 115

What is wrong with this code? Swift optionals

What is wrong with this code?

        if documentArray != nil { rowCount = documentArray?.count } else { rowCount = 1 }

Xcode tells me I need to add an ! to the end of count, then when I add it it tells me I need to delete it. This makes no sense to me. I'm ready checking if the NSArray exists so if it does then it should have a count. All this optional crap is really starting to piss me off. What am I doing wrong?

Upvotes: 0

Views: 67

Answers (1)

Adam Russell
Adam Russell

Reputation: 46

Xcode is mad because you are using optional chaining with documentArray?.count. You should use documentArray!.count to force unwrap the value.

Another approach, conditional binding is sometimes an easier way to not have to worry about these sorts of things.

if let documentArray = documentArray {
    rowCount = documentArray.count
} else {
    rowCount = 1
}

Upvotes: 3

Related Questions