Search code examples
xcodeswiftxcode6swift-playgroundxcode6-beta6

Is Swift type-inference contradicting itself here?


Here's my test code:

var myDict: [String: AnyObject] = ["k":"v"]

var a = myDict["k"]
var b = a as String

var c = myDict["k"] as String

Here's my Swift playground in Xcode6-beta6:

Playground

According to the rules of type inference, doesn't complaining about c logically contradict not-complaining about b?


Solution

  • I believe that this is a bug. Part of what is going on here is that String is not an object. If you change the first line to:

    var myDict: [String: Any] = ["k":"v"]
    

    then everything is fine. So, given that string is not an object, casting a variable of type AnyObject? to a String should definitely yield an error. And, since the compiler has already decided that a is of type AnyObject? it should complain about casting a to a String.

    Note that if you change the last line to:

    var c = myDict["k"] as NSString
    

    the error goes away supporting the notion that the issue is that String is not an object. You get the same complaint if you put an Int as the value in the array and try to cast that to an Int.

    Update:

    So the plot thickens. If you don't import Foundation or import something that imports Foundation, then you get additional errors. Without Foundation:

    enter image description here

    So clearly some of this has to do with the dual nature of Strings as non-objects and NSStrings as objects and the ability to use Strings as NSStrings when Foundation is imported.