简体   繁体   中英

Cannot assign value of type String to type AnyObject? Swift 3.0

I am suddenly getting this error for a dictionary of type:

var parameters = [String: AnyObject]()

and then if I try:

parameters["cancelled_by"] = someUser ?? ""

I am getting the error as :

Cannot assign value of type String to type AnyObject?

This is for Swift 3.0 . What am I doing wrong here? Why doesn't it work?

String is the value type . AnyObject only accepts reference types . So in order to add both value types and reference types in Dictionary use Any instead of AnyObject , ie

var parameters = [String: Any]()

This is an addition to Swift 3.0.

I'm starting with Swift 3 right now, a bit late... however, until Swift 2.2 some Swift value types were automatically bridged to the corresponding foundation reference types, such as String to NSString , Dictionary<> to NSDictionary , and so forth. It looks like this automatic bridging has been removed in Swift 3.

There are cases where turning a [String : AnyObject] into [String : Any] makes sense, in others it doesn't, depending on what you're doing. In my current case, where I need reference types, it doesn't.

So I am solving the problem by requesting an explicit bridging, by casting to AnyObject :

var dictionary: [String : AnyObject] = [:]
dictionary["valueType"] = "Value Type" // Error
dictionary["referenceType"] = "Reference Type" as AnyObject // OK

For reference:

let text = "Text"
let asAny = text as Any
let asAnyObject = text as AnyObject
let asNSString: NSString = text as NSString

type(of: text) // Prints String.Type
type(of: asAny) // Prints String.Type
type(of: asAnyObject) // Prints _NSContiguousString.Type
type(of: asNSString) // Prints _NSContiguousString.Type

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM