Swift generics doesn't work as expected with JSON dictionary came from Objective-C parser -


i have function retrieve non optional value json dictionary. takes 3 params: dictionary, key , default value case no value in dictionary or value have wrong type

func valuefromjsondict<t>(dict:[nsobject: anyobject]?, key: nsobject, defaultvalue: t) -> t {     if let value = dict?[key] as? t {         return value     }     return defaultvalue } 

the problem returns default value.

title = valuefromjsondict(dict, "title", "") 

but if same thing without generics works fine:

title = { () -> string     if let value = dict?["title"] as? string {       title = value    } else {       return ""    } }() 

this parsed json dict coming objective-c parser , if println dynamictype of value dict __cfnsstring, t.self swift.string, swift unable figure out types probably

how make work?

what dict object like?

here suggest:

typealias jsonobject = [string: anyobject]  func valuefromjson<t>(json: jsonobject?, key: string, defaultvalue: t) -> t {     if let value = json?[key] as? t {         return value     }     return defaultvalue }  let json = ["name": "sir lancelot",             "quest": "to seek holy grail",             "favorite color": "blue..."]  let name = valuefromjson(json, "name", "sir not appearing in film") 

Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -