1

After run following code in playgroud, why x value is 2? Is there anything wrong with swift generic type and "is" operator? class Item {}

class Campaign: Item {}

class AdGroup : Item {}

class A<T: Item> {
    func val() -> Int{
        let item = T()
        if item is Campaign {
            return 1
        } else {
            return 2
        }
    }
}

var m = A<Campaign>()
let x = m.val()
Bruno Bu
  • 63
  • 1
  • 1
  • 4
  • 2
    Looks like a bug. I get "2" in the Debug configuration and "1" in the Release configuration. (Which reminds me of http://stackoverflow.com/questions/25838032/optional-binding-succeeds-if-it-shouldnt which also gives wrong results in Debug mode only.) – Martin R Jan 12 '15 at 10:41
  • It’s debatable whether this is a bug or just exhibiting undefined behaviour. Strictly speaking, “is” is not allowed when the check is guaranteed to succeed (e.g. `10 as Int` isn’t allowed). In this instance “is” is guaranteed to succeed because `T` is a `Campaign` (when called as shown), so perhaps it should yield a compilation error. – Airspeed Velocity Jan 12 '15 at 12:21
  • Strange ... What should happen in case `Campaign` requires a parameter to be initialised. (i.e. `Campaign` doest not have `int()`)? It appears the `Campaign` initialiser is not called. – Matteo Piombo Jan 12 '15 at 13:17
  • Not shown here is the definition for `Item` – for this code to compile, it has to define an `init()` method. If `Item` defined, say, an `init` that took a `String` instead, you could use that in `val()` instead, but not `init()`. Interestingly, if `Item` is defined as a protocol rather than a class, it makes this problem go away (though that can't be what is happening here since `Campaign` would need to be defined differently). – Airspeed Velocity Jan 12 '15 at 14:16
  • related: http://stackoverflow.com/q/26280176/3804019 – rintaro Jan 13 '15 at 12:36

0 Answers0