swift - Grabbing values from a dictionary in a more elegant way -


i've been playing swift , getting quite tortured! consider:

var mydict : dictionary <string, string>  //do magic populate mydict values <magic being done>   //now mydict has values.  let's parse out values of mydict  //this doesn't work let title : string  = mydict["title"]  //this let title : string? mydict["title"] 

this because isn't known whether key in dictionary. want say, though, "if title key in dictionary, give me value, else, give me empty string"

i write:

var mytitle : string if let title : string = mydict["title"] {     mytitle = title } else {     mytitle = "" } 

i believe works...but...it's quite lot of code each key of dictionary. have ideas in swift world on how supposed written?

rd

you write extension on optional:

extension optional {     /// unwrap value returning 'defaultvalue' if value nil     func or(defaultvalue: t) -> t {         switch(self) {             case .none:                 return defaultvalue             case .some(let value):                 return value         }     } } 

then can do:

mydict["title"].or("") 

this work optionals.

note: started module add common helpers or on optional swift.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -