简体   繁体   中英

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

I was using swift 1.2 and everything was going fine. after upgrading my Xcode to 7 . I faced some weird problems.

My code was :

let postData : AnyObject = ["username":username , "password":password] ;

I need this variable to be 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 a Anyobject for post Data header.

The error is

 Value of type '[String : String?]' does not conform to specified type 'AnyObject' 

can any one help me?

I assume you are passing parameters to a request which require key as String and value can be AnyObject . Try this:

let postData: [String: AnyObject] = ["username":username , "password":password]

Also make sure username and password are not optional, and in that case, use ! to unwrap them if you are sure values wil be there.

let postData: [String: AnyObject] = ["username":username!, "password":password!]

or you can use

let postData: [String: AnyObject] = ["username":username ?? "", "password":password ?? ""]

The problem is your password variable is an Optional<String> . This means the conversion from Swift dictionary to AnyObject (I think it tries to convert it to an NSDictionary) will fail.

If you do

let postData : AnyObject = ["username":username , "password":password!]

It should work unless the password is nil (check that before creating the dictionary)

If you want to be able to have null passwords in the output, you can do this in your 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"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM