Tuesday 15 July 2014

swift - Get string from userInfo Dictionary -



swift - Get string from userInfo Dictionary -

i have userinfo dictionary uilocalnotification. there easy way string value when using implicit unwrapping?

if allow s = userinfo?["id"]

gives me anyobject have cast string.

if allow s = userinfo?["id"] string

gives me error stringliteralconvertable

just didn't want have declare 2 variables string - 1 literal disclose , var casted string.

edit

here method. doesn't work either - (nsobject, anyobject) not convertible string on if statement.

notification in schedulednotifications { // optional chainging allow userinfo = notification.userinfo if allow id = userinfo?[ "id" ] as? string { println( "id found: " + id ) } else { println( "id not found" ) } }

i don't have in question, besides getting way work, i'd have

if allow s = notification.userinfo?["id"] string

you want utilize condition cast using as?:

(note: works xcode 6.1. xcode 6.0, see below)

if allow s = userinfo?["id"] as? string { // when here, know "id" valid key // , value string. }

this build safely extracts string userinfo:

if userinfo nil, userinfo?["id"] returns nil due optional chaining , conditional cast returns variable of type string? has value of nil. optional binding fails , block not entered.

if "id" not valid key in dictionary, userinfo?["id"] returns nil , proceeds previous case.

if value type (like int), conditional cast as? homecoming nil , proceeds above cases.

finally, if userinfo not nil, , "id" valid key in dictionary, , type of value string, conditional cast returns optional string string? containing string. optional binding if let unwraps string , assigns s have type string.

for xcode 6.0, there 1 additional thing must do. need conditionally cast nsstring instead of string because nsstring object type , string not. apparently improved handling in xcode 6.1, xcode 6.0 following:

if allow s:string = userinfo?["id"] as? nsstring { // when here, know "id" valid key // , value string. }

finally, addressing lastly point:

notification in schedulednotifications { if allow id:string = notification.userinfo?["id"] as? nsstring { println( "id found: " + id ) } else { println( "id not found" ) } }

dictionary swift optional

No comments:

Post a Comment