Get string from user info dictionary

I have a userInfo dictionary from UILocalNotification. Is there an easy way to get a String value when using implicit sweep?

if let s = userInfo?["ID"] 

Gives me AnyObject, which I should pass to the string.

 if let s = userInfo?["ID"] as String 

Gives me an error about StringLiteralConvertable

It was just not necessary to declare two variables in order to get a string - one literal for a spread and another var for a cast line.

Edit

Here is my method. This also does not work - I get (NSObject, AnyObject) not converted to String in if statement.

  for notification in scheduledNotifications { // optional chainging let userInfo = notification.userInfo if let id = userInfo?[ "ID" ] as? String { println( "Id found: " + id ) } else { println( "ID not found" ) } } 

I do not have this in my question, but, besides this way to work, I would like to have

 if let s = notification.userInfo?["ID"] as String 
+5
source share
1 answer

Do you want to use the condition using as? :

(Note: this works for Xcode 6.1. For Xcode 6.0 see below)

 if let s = userInfo?["ID"] as? String { // When we get here, we know "ID" is a valid key // and that the value is a String. } 

This construct safely retrieves a string from userInfo :

  • If userInfo is nil , userInfo?["ID"] returns nil due to an optional chain, and the conditional listing returns a variable of type String? which matters nil . Then, the optional binding fails and the block is not entered.

  • If "ID" not a valid key in the dictionary, userInfo?["ID"] returns nil and works as in the previous case.

  • If the value is another type (e.g. Int ), then conditional listing as? will return nil and will act as in the above cases.

  • Finally, if userInfo not nil , but "ID" is a valid key in the dictionary and the value type is String , then the conditional listing returns an optional String? containing the string. The optional if let binding then expands the String and assigns it to s , which will be of type String .


For Xcode 6.0, there is one more thing you have to do. You should conditionally drop NSString instead of String , because NSString is a type of object, and String is not. They seem to have improved processing in Xcode 6.1, but for Xcode 6.0, follow these steps:

 if let s:String = userInfo?["ID"] as? NSString { // When we get here, we know "ID" is a valid key // and that the value is a String. } 

Finally, referring to your last point:

  for notification in scheduledNotifications { if let id:String = notification.userInfo?["ID"] as? NSString { println( "Id found: " + id ) } else { println( "ID not found" ) } } 
+19
source

Source: https://habr.com/ru/post/1204528/


All Articles