[英]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?
无法将String类型的值分配为AnyObject类型?
This is for Swift 3.0
. 这是针对
Swift 3.0
。 What am I doing wrong here? 我在这里做错了什么? Why doesn't it work?
为什么不起作用?
String
is the value type . String
是值类型 。 AnyObject
only accepts reference types . AnyObject
仅接受引用类型 。 So in order to add both value types and reference types in Dictionary
use Any
instead of AnyObject
, ie 因此,为了在
Dictionary
添加值类型和引用类型,请使用Any
而不是AnyObject
,即
var parameters = [String: Any]()
This is an addition to Swift 3.0. 这是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. 我现在从Swift 3开始,有点晚了……但是,直到Swift 2.2某些Swift值类型自动桥接到相应的基础引用类型,例如
String
到NSString
, Dictionary<>
到NSDictionary
等等。 。 It looks like this automatic bridging has been removed in Swift 3. 看来此自动桥接已在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. 在某些情况下,将
[String : AnyObject]
转换为[String : Any]
是有意义的,在其他情况下则没有意义,这取决于您在做什么。 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
: 所以我通过请求显式桥接,强制转换为
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.