KexAri KexAri - 2 months ago 48
iOS Question

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 get the error: 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?

Answer

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, i.e.

var parameters = [String: Any]()

This is an addition to Swift 3.0.