Is swift output inconsistent here?

Here is 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 is my quick playground in Xcode6-beta6:

Playground

In accordance with the rules of type inference, without complaining about clogically contradict without complaining about b?

+4
source share
3 answers

I think this is a mistake. Part of what is happening here is that which is Stringnot an object. If you change the first line to:

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

. , , , AnyObject? String . , a AnyObject?, a String.

, :

var c = myDict["k"] as NSString

, , , String . , Int Int.

, . import Foundation , Foundation, . :

enter image description here

, , String - NSString String NSString Foundation.

+2

, Dictionary :

subscript (key: Key) -> Value?
subscript (i: DictionaryIndex<Key, Value>) -> (Key, Value) { get }

- , , ; .

. , DictionaryIndex - , - .

, ( , , String), (, ), . , . .

+1

.

var c = myDict["k"] as AnyObject! as String   // "v"

, , Swift , , . , var a = myDict["k"] . AnyObject?, :

var c = myDict["k"] as AnyObject? as String   // "v"

, , "k", . nil String?.

0

All Articles