Gavin
Gavin

Reputation: 2824

Swift 3 Contextual type 'AnyObject' Cannot be used with dictionary literal

I was porting from swift2.3 to swift3 and ran into the following problem.

I am trying to return a dictionary of value dictionary in the function below. But is getting the error Contextual type 'AnyObject' Cannot be used with dictionary literal

I have tried manually bridging the value as AnyObject after looking for some answers but to no avail.

typealias Payload = [String: AnyObject]

func toCreatePayload() -> Payload {
    let payload: [String: [String:AnyObject]] =
        ["saving_rule": ["description": title as AnyObject,
                         "amount": amount! as AnyObject,
                         "background_color": (backgroundColor?.toHexString())! as AnyObject,
                         "saving_rule_category_id": category!.remoteId as AnyObject,
                         "saving_rule_sub_category_id": subCategory != nil ? subCategory!.remoteId : ("" as AnyObject),
                         "saving_rule_condition_id": condition != nil ? condition!.remoteId : ("" as AnyObject),
                         "saving_rule_condition_customizations_attributes": customizations.map({$0.toCreatePayload()}) as AnyObject,
                         "suspended": "false"] as AnyObject
        ]
    return payload as [String:AnyObject]
}

Upvotes: 2

Views: 1162

Answers (1)

orxelm
orxelm

Reputation: 1144

Use Any instead of AnyObject :

func toCreatePayload() -> Payload {
    let payload: [String: [String:Any]] =
        ["saving_rule": ["description": title,
                         "amount": amount!,
                         "background_color": (backgroundColor?.toHexString())!,
                         "saving_rule_category_id": category!.remoteId,
                         "saving_rule_sub_category_id": subCategory != nil ? subCategory!.remoteId : "",
                         "saving_rule_condition_id": condition != nil ? condition!.remoteId : "",
                         "saving_rule_condition_customizations_attributes": customizations.map({$0.toCreatePayload()}),
                         "suspended": "false"]
        ]
    return payload
}

The difference:

  • Any can represent an instance of any type at all, including function types and optional types.
  • AnyObject can represent an instance of any class type.

Upvotes: 1

Related Questions