0
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?

Dew Time
  • 818
  • 9
  • 10
  • The [optional chaining](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html) expression returns an optional value and because you can't compare an `Optional` to an `Int` you need to unwrap it. – Keiwan Jun 24 '17 at 21:32
  • 3
    *"So why do I need the exclamation mark?"* So you can have the pleasure of watching your app crash when `tweet` is `nil`. :) – rmaddy Jun 24 '17 at 21:37
  • So why is it not giving me an error anymore? if tweet?.media.count == 0 { return "" } else { return "Images" } – Dew Time Jun 24 '17 at 21:49
  • Please don't post code in comments. [Edit] your question if you have additional information. – rmaddy Jun 24 '17 at 21:50
  • 1
    @DewTime: You can test optional values for *equality* (== 0), but you cannot *compare* them (< 0) in Swift 3. Compare https://stackoverflow.com/questions/39251005/strange-generic-function-appear-in-view-controller-after-converting-to-swift-3. – Martin R Jun 24 '17 at 21:56
  • BTW, it doesn't make sense to use optional chaining to only later force unwrap it. Easier would be `if tweet!.media.count < 0 { ... }`. It's less convoluted. Or, better, there are a ton of ways of tackling to gracefully unwrap it without the `!` forced unwrapping operator (such as what Tim suggested below). But all of that having been said, can `count` ever be less than zero? That doesn't make sense to me. – Rob Jun 24 '17 at 23:12

1 Answers1

1

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.

Tim
  • 59,527
  • 19
  • 156
  • 165
  • 4
    I wish Xcode would stop recommending the `!` operator. There would be 5,000 less Swift questions posted on SO about crashes due to force-unwrapping. – rmaddy Jun 24 '17 at 21:39
  • Ok so now for whatever reason, xcode is not forcing me to do it anymore. I have taken off the exclamation mark and it lets me compile. I don't get why sometimes its' telling me to do something then later its ok. – Dew Time Jun 24 '17 at 21:41