karl karl - 3 months ago 6
iOS Question

Unwrapping and checking multiple optionals on single line

I currently use this pattern

do {

if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {

let valid: Int? = 1
let status: String? = "ok"

if let v = jsonResult["valid"] as? Int, s = jsonResult["status"] as? String {
if v == valid && s == status{
//Do something
}
}
}


Is this the optimal method to check that v == 1 and s == "ok"

Or is it possible to do something like this answer, would it be better ?
Answer(Unwrapping multiple optionals in a single line)

if let v = jsonResult["valid"] as? Int, s = jsonResult["status"] as? String
where is(v, valid && s, status)


Any help is appreciated, thank you.

Answer

If you don't need v and s inside of the body of the if, you can just do the comparison directly:

if jsonResult["valid"] as? Int == 1 && jsonResult["status"] as? String == "ok" {
    // Do something
}
Comments