swift - cannot return String in function -
i having trouble casting option anyobject string. whenever try call fuction program crashes (lldb)
. function.
func name() -> string { print(attributes["name"]) print(attributes["name"]! as! string) let name = attributes["name"]! as! string return name }
the output prints is:
optional(optional(josh)) josh (lldb)
thanks in advance help!
lets attributes
defined follow
var attributes: nsmutabledictionary? = nsmutabledictionary()
and can populated follow
attributes?.setvalue("walter white", forkey: "name")
optionals
you should design name()
function return string
or nil
(aka string?
optional
type)
func name() -> string? { guard let attributes = attributes, name = attributes["name"] as? string else { return nil } return name }
the same logic can written way
func name() -> string? { return attributes?["name"] as? string }
now if valid string
value found inside attributes
key name
returned. otherwise function return nil
.
invoking function
when using function should unwrap result this
if let name = name() { print(name) // prints "walter white" }
Comments
Post a Comment