4

This code worked just fine in Swift 2.3 and I don't understand why I have to unwrap TestClass to check if number is bigger than 4. This is whole point of chaining optionals, to save additional call.

Now to make this work, I have to check if testClass != nil (or use implicit unwrap with if let statement) and then check count.

Is this really the only way?

import UIKit

class testClass
{
    var optionalInt:Int?
}

var test:testClass?

if test?.optionalInt > 4
{

}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
user2282197
  • 65
  • 1
  • 5
  • Sorry about the bad news on this one, but very glad you asked about it, as this is liable to come up a lot in one form or another. – matt Sep 10 '16 at 15:43
  • Related: http://stackoverflow.com/questions/39251005/strange-generic-function-appear-in-view-controller-after-converting-to-swift-3. – Martin R Sep 10 '16 at 19:52

4 Answers4

5

It's not a bug. It is, alas, intentional. Implicit unwrapping of optionals in comparisons (>) has been removed from the language.

So, the problem now is that what's on the left side of the > is an Optional, and you can no longer compare that directly to 4. You have to unwrap it and get an Int, one way or another.

matt
  • 515,959
  • 87
  • 875
  • 1,141
4

First of all, where are you initialising your test var? Of course it'll be nil if you don't give it a value!

And regarding optional chaining, what's the issue writing :

if let optionalInt = test?.optionalInt, optionalInt > 4
{

}

As always, safety > brevity.

Jonas Zaugg
  • 3,005
  • 2
  • 15
  • 21
0

Optional comparison operators are removed from Swift 3. SE-0121

You need to write something like this:

if test?.optionalInt ?? 0 > 4
{

}
OOPer
  • 47,149
  • 6
  • 107
  • 142
0

This could also happen on Guard statement. Example:

var playerLevels = ["Harry": 25, "Steve": 28, "Bob": 0]

for (playerName, playerLevel) in playerLevels {

guard playerLevels > 0 else {//ERROR !!
    print("Player \(playerName) you need to do the tutorial again !")
    continue
}

print("Player \(playerName) is at Level \(playerLevels)")

}

LAOMUSIC ARTS
  • 642
  • 2
  • 10
  • 15