简体   繁体   中英

How to cast from NSDictionary to Dictionary ? swift 3

please have a look at the bellow code:

class A{


   class func func1(params post_params:NSDictionary!){

                let post_paramsValue =  post_params as? Dictionary<String,Any>!
                self.func2(params: post_paramsValue)
    }

    class func func2(post_params:Dictionary<String,Any?>!)
}
############### OBJECTIVE C ###############
[A func1:nil];

on swift 3 the code crash on self.func2(params: post_paramsValue) with this exception:

fatal error: unexpectedly found nil while unwrapping an Optional value

although it run on swift 2

  1. func2 can accept nil values! so why it crashes ?

  2. why i don't receive build error if there is a problem with casting Dictionary<String,Any>! to Dictionary<String,Any?>! ?

EDIT1:

Why the bellow code doesn't crash ?

NSMutableDictionary *infoToUpload = [[NSMutableDictionary alloc]init];
infoToUpload[@"lookitChatId"] = @"";
[A func1:nil];

EDIT2:

I think i should write the func1 in this way to make sure that the code won't crash: (i don't why ?)

class func func1(params post_params:NSDictionary!){

                  if  let post_paramsValue =  post_params as? Dictionary<String,Any>!{
                           self.func2(params: post_paramsValue)
                   }else{

                         self.func2(params: nil)
                     }

        }

Here is you code but with no crash.

class A {
    class func func1(params post_params: NSDictionary!){
        let post_paramsValue = post_params as? Dictionary<String,Any>
        self.func2(post_params: post_paramsValue)
    }
    class func func2(post_params:Dictionary<String,Any>!) {
    }
}

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