user979331 user979331 - 5 months ago 12
Swift Question

Swift - dictionary item to label

I am trying to assign the value of Dictionary item to label. This Dictionary is inside an array.

when I print this item like so:


it returns


which is the correct value. But I don't know why the Optional() is there.

Anyways when I try to assign this value to a label like so:

self.LData1.text = wsQAshowTagArray![0]["LData1"]

my code goes black and I get this error, only when I run it.

enter image description here

Why am I getting this error and how do I assign this to a label?


wsQAshowTagArray![0]["LData1"] is an optional Int. You can force unwrap it by appending !:

let someInt = wsQAshowTagArray![0]["LData1"]!

Then you could put it in a string like so:

LData1.text = "\(someInt)"

Or as a one-liner:

LData1.text = "\(wsQAshowTagArray![0]["LData1"]!)"

Note that this code will crash because you're force-unwrapping using !. You should really use if let or guard let instead. Optionals are a fundamental part of the Swift language. You should read the docs on them (they're short).