1

I have this Dictionary

var detailItem: Dictionary?

I am trying to get the Any and convert it to a String and then assign to UILabel like so:

self.firstName.text = detail!["firstname"] as? String

Fatal error: Unexpectedly found nil while unwrapping an Optional value

Which I dont understand because first name is not nil, its James (not "James") but just James, if I print it I can see it:

print(detail!["firstname"])

What am I doing wrong?

How to do I assign Any to UiLabel text?

user979331
  • 11,039
  • 73
  • 223
  • 418

1 Answers1

1

The safest way to do this is to unwrap the optional string value from your dictionary.

if let firstName = detail?["firstname"] as? String {
    self.firstName?.text = firstName
}

This ensures your label's text will only get set when there is a value for "firstname" in your Dictionary.

If that still crashes then your label might be nil. If your using an outlet it might not be set.

naturaln0va
  • 755
  • 6
  • 8