Lester
Lester

Reputation: 731

Contextual type 'Any' cannot be used with dictionary literal Swift

I use this code in two files, but only one file shows this error.

Contextual type 'Any' cannot be used with dictionary literal

Why? This 2 code is the same, why only one got the error? What's wrong in this code?

let userId = user!["userId"] as! String
let bookCid = NSUUID().uuidString
let param = ["message":"addAccBook",
                 "accountbook":
                    [
                        "bookcid": bookCid!,
                        "accbookname": "",
                        "accbooktype": "",
                        "category": "",
                        "user": userId
    ]] as [String:Any]

enter image description here enter image description here

Upvotes: 3

Views: 2881

Answers (1)

vadian
vadian

Reputation: 285290

The error is misleading. The actual error is

Cannot force unwrap value of non-optional type 'String'

uuidString returns an non-optional String, therefore you must not add an exclamation mark

let userId = user!["userId"] as! String
let bookCid = NSUUID().uuidString

let param : [String:Any] = ["message":"addAccBook",
                            "accountbook":
                               ["bookcid": bookCid,
                                "accbookname": "",
                                "accbooktype": "",
                                "category": "",
                                "user": userId]]

Rather than bridge cast the type I recommend to annotate it.

Upvotes: 4

Related Questions