swift - Downcasting and optional: is this code idiomatic? -
i want make sure getting syntax right in both cases class super or derived class? issues following code?
class { } class b : { var y = 42 } // #1 func test(x: a?) -> string { return (x as? b!)?.y == 42 ? "yes" : "no" } let a: a? = a() print(test(a)) let b: b? = b() print(test(b)) example of code using syntax (datataskurl):
objc:
if ([response iskindofclass:[nshttpurlresponse class]] && [(nshttpurlresponse *)response statuscode] != 200) { swift objc-like:
if response.iskindofclass(nshttpurlresponse.self) && (response as! nshttpurlresponse).statuscode != 200 { better swift?
if (response as? nshttpurlresponse!)?.statuscode == 200 {
this swift way (it both safe , nice):
if (response as? nshttpurlresponse)?.statuscode == 200 { it uses conditional casting , optional chaining both test class nshttpurlresponse , statuscode 200. note don't need ! after nshttpurlresponse.
if response class, (response as? nshttpurlresponse) return nil, entire optional chain return nil , since nil != 200 test fail.
Comments
Post a Comment