swift2 - Swift 2: How can i assign a dictionary to AnyObject? -


i using swift 1.2 , going fine. after upgrading xcode 7 . faced weird problems.

my code :

let postdata : anyobject = ["username":username , "password":password] ; 

i need variable anyobject, because

    let jsonobject : anyobject = postdata ;     let jsonstring = jsonstringify(jsonobject)     let data1 = jsonstring.datausingencoding(nsutf8stringencoding)      let task1 = nsurlsession.sharedsession().uploadtaskwithrequest(request, fromdata: data1) {         (data, response, error) -> void in 

needs anyobject post data header.

the error is

 value of type '[string : string?]' not conform specified type 'anyobject'  

can 1 me?

the problem password variable optional<string>. means conversion swift dictionary anyobject (i think tries convert nsdictionary) fail.

if

let postdata : anyobject = ["username":username , "password":password!] 

it should work unless password nil (check before creating dictionary)

if want able have null passwords in output, can in dictionary

let postdata : [string : anyobject] = ["username":username , "password":password ?? nsnull()] 

the following works

let pw: string? = "pw" let pw2: string? = nil var foo: [string : anyobject] = ["bar" : pw ?? nsnull(), "baz" : pw2 ?? nsnull()]  let data = try nsjsonserialization.datawithjsonobject(foo, options: nsjsonwritingoptions.prettyprinted)  let str = nsstring(data: data, encoding: nsutf8stringencoding)!  print(str) 

and prints

{   "baz" : null,   "bar" : "pw" } 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -