Dew Time
Dew Time

Reputation: 878

Why do I need to wrap this line in an exclamation? swift 3

if (tweet?.media.count)! < 0

Tweet is a class of type optional Tweet

media is of type [mediaitem]

count is of type Int

So why do I need the exclamation mark?

Upvotes: 0

Views: 96

Answers (1)

Tim
Tim

Reputation: 60110

Since tweet is optional, its value might be nil. Using optional chaining (the ?. operator between tweet and media) means that the rest of the expression might also be nil – after all, it's not possible to get a non-nil array of media items from a nil tweet.

At the end of the expression, then, you're left with an optional Int, which isn't directly comparable to 0. That's why the compiler suggests you force-unwrap the count using the ! operator.

I personally think there's a better way – instead of force-unwrapping, you can check whether tweet is nil up front:

if let tweet = tweet, tweet.media.count < 0 {
    // …
}

Using if let like this only proceeds with the conditional if tweet is not nil. Then, in the expression that follows, you can use the unwrapped non-Optional tweet for the rest of your calculations.

Upvotes: 1

Related Questions