shilei365
shilei365

Reputation: 223

App crashed when getting string from Dictionary (swift)

I converted a JSON to Dictionary and got some String by

title = json?.objectForKey("Titel_Live") as! String

But some times app will be crashed. I cannot reproduce this problem, just get information from crash reports.

Could someone help me and tell why? Thanks

Error at line 163 enter image description here

Crash reports Crash reports

Upvotes: 0

Views: 1798

Answers (2)

Pavan gopal
Pavan gopal

Reputation: 81

You should not force the casting to String.

You can try :-

title = json?.objectForKey("Title_Live") as? String (if title is optional variable) if title is not optional then use:

title = (json?.objectForKey("Title_Live") as? String ?? "")

Because objectForKey will return nil if no value is associated with that key and force casting nil to String fails and causes crash.

Upvotes: 2

Buntylm
Buntylm

Reputation: 7383

title = json?.objectForKey(“Titel_live”) as! String

This line of code where you are doing force unwrapped (Don't force the cast using !) is the cause means if object with key Titel_live dot not find then should be crashed, better go with optional chaining or use gaurd but yes your Json does't contain any object with key Titel_live(may be spelling mistake or object is array so validate once).

//better go like this check if exist or not.
if let t =  json?.objectForKey(“Titel_live”) {
title = t
}

Upvotes: 4

Related Questions