从userInfo Dictionary获取字符串

Bri*_*ian 5 dictionary optional swift

我有来自UILocalNotification的userInfo字典.使用隐式展开时是否有一种简单的方法来获取String值?

if let s = userInfo?["ID"]
Run Code Online (Sandbox Code Playgroud)

给我一个AnyObject,我必须强制转换为字符串.

if let s = userInfo?["ID"] as String 
Run Code Online (Sandbox Code Playgroud)

给我一个关于StringLiteralConvertable的错误

只是不想声明两个变量来获取字符串 - 一个用于解包的文字和另一个用于转换字符串的var.

编辑

这是我的方法.这也不起作用 - 我得到(NSObject,AnyObject)在if语句中不能转换为String.

  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" )
    }
  }
Run Code Online (Sandbox Code Playgroud)

我没有在我的问题中,但除了这种方式工作,我想真的有

if let s = notification.userInfo?["ID"] as String 
Run Code Online (Sandbox Code Playgroud)

vac*_*ama 19

你想用一个条件投as?:

(注意:这适用于Xcode 6.1.对于Xcode 6.0,请参见下文)

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.
}
Run Code Online (Sandbox Code Playgroud)

此构造安全地从userInfo以下位置提取字符串

  • 如果userInfonil,userInfo?["ID"]返回nil由于可选链接条件铸造返回类型的变量String?,其具有的值nil.然后,可选绑定失败,并且未输入块.

  • 如果"ID"不是字典中的有效键,则userInfo?["ID"]返回nil并像前一种情况一样继续.

  • 如果值是另一种类型(如Int),那么条件转换 as?将返回nil并且它像上面的情况一样继续.

  • 最后,如果userInfo不是nil,并且"ID"是字典中的有效键,并且值的类型是a String,则条件转换返回String?包含该字符串的可选字符串.然后,可选绑定 if let将打开String并将其分配给s具有类型的绑定String.


对于Xcode 6.0,您还必须做一件事.你需要有条件地转换为to NSString而不是to String因为NSString是一个对象类型而String不是.他们显然改进了Xcode 6.1中的处理,但对于Xcode 6.0,请执行以下操作:

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.
}
Run Code Online (Sandbox Code Playgroud)

最后,解决你的最后一点:

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