lukas_o lukas_o - 1 year ago 89
Swift Question

swift using guard and typechecking in one line

I like using guard and came across the situation where I want to use where for a type check as well:

guard let status = dictionary.objectForKey("status") as! String! where status is String else { ...}

xCode complains correctly that it's always true, changing it to:

guard let status = dictionary.objectForKey("status") where status is String else { ...}

I cannot cast it afterwards.

How can I do this in one line? Is there a way?

Answer Source

Probably you want this?

guard let status = dictionary["status"] as? String else {
    // status does not exist or is not a String

// status is a non-optional String
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download