ios - Not using unwrapping in guard statements -
i understand use of optionals enough know when necessary unwrap optional using exclamation point. why exclamation point isn't needed in guard statement?
this code works , compiles doesn't use exclamation points:
struct blog{ var author:string? var name: string? } func bloginfo2(blog:blog?){ guard let blog = blog else { print("blog nil") return } guard let author = blog.author, name = blog.name else { print("author or name nil") return } print("blog:") print(" author: \(author)") print(" name: \(name)") }
this code works if put exclamation points:
struct blog{ var author:string? var name: string? } func bloginfo2(blog:blog?){ guard let blog = blog! else { print("blog nil") return } guard let author = blog.author!, name = blog.name! else { print("author or name nil") return } print("blog:") print(" author: \(author)") print(" name: \(name)") }
isn't little contradictory or can explain why exclamation point isn't needed?
guard let unwrapped = optional
optional binding (no link available directly correct book section, unfortunately). safely tries unwrap value in optional. if there value, unwrap succeeds, , value assigned given name.
you should heavily favor use of optional bindings, either guard
or if
(the difference scope of "unwrapped" name) on use of forced unwrapping !
. failed force unwrap fatal error; program crash.
Comments
Post a Comment