objective c - Swift nil values behaviour -
can send messages nil
in swift
same way can in objective-c
without causing crash?
i tried looking documentation , couldn't find relating this.
not exactly, have use optional chaining. in swift, instance can nil
if declared "optional" type. looks this:
var optionalstring : string?
notice ?
after string
makes possible nil
you cannot call method on variable unless first "unwrap" it, unless use aforementioned optional chaining.
with optional chaining can call multiple methods deep, allow nil value returned:
var optionalresult = optionalstring.method1()?.method2()?.method3()
optionalresult
can nil. if of methods in chain return nil, methods after not called, instead optionalresult gets set nil.
you cannot deal directly optional value until explicitly handle case nil. can in 1 of 2 ways:
force unwrap blindly
println(optionalstring!)
this throw runtime error if nil, should sure not nil
test if nil
you can using simple if statement:
if optionalstring { println(optionalstring!) } else { // nil }
or can assign scoped variable don't have forcefully unwrap it:
if let nonoptionalstring = optionalstring { println(nonoptionalstring) } else { // nil }
Comments
Post a Comment