0

I am executing the following code:

let createByDicc = [
        "nickname" : self.createdBy?.nickname,
        "avatar" : self.createdBy?.avatar,
        "id" : self.createdBy?.id
        ] as! [String : String]

    let dicc = [
        "channelId" : self.channelId!,
        "createBy" : createByDicc,
        "message" : self.message!,
        "type" : "message",
        "replyTo" : "nmartello"
        ] as! [String : String]

I am positive that all the variables I am using are not null (self.createdBy?.nickname etc have a string assigned). If I comment out the

"createBy" : createByDicc'

it works just fine, but if not I get Unexpectedly found nil when unwrapping an Optional value . I need this Dictionary inside a Dictionary for the payload of a WS I need to call using Alamofire and I am not sure what it's wrong here. Any ideas?

Ignacio Oroná
  • 4,371
  • 1
  • 19
  • 25
  • 2
    also... `dicc` should be `[String:Any]` as you are loading a dictionary in it – GIJOW Mar 19 '18 at 21:11
  • Check the definition of `createByDicc` as it hasn't been assigned a value – George_E -old Mar 19 '18 at 21:12
  • Do all properties of `self.createdBy` (especially `id`) contain a string? Looks like the `createByDicc` can't be casted to `[String: String]` type. – Dan Karbayev Mar 19 '18 at 21:13
  • Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Cristik Mar 19 '18 at 21:26
  • Never (force) cast a dictionary to a specific type. Annotate the type `let dicc : [String : String] = [ ...` then you will get a compiler error which leads you to the issue – vadian Mar 19 '18 at 21:26

1 Answers1

1

First thing, you say that dicc is a [String: String] dictionary, but your createByDicc is not a string, it is another dictionary. so your dicc should be [String: Any].

Second, It is a very good practice to never force unwrap your optionals. Try to either do a if let or guard statement and save the values or just use Nil Coalescing: self.message ?? ""

gmogames
  • 2,993
  • 1
  • 28
  • 40