dictionary - 从 userInfo 字典中获取字符串

标签 dictionary swift option-type

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

if let s = userInfo?["ID"]

给我一​​个必须转换为字符串的 AnyObject。

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

给我一​​个关于 StringLiteralConvertable 的错误

只是不想声明两个变量来获取字符串 - 一个用于解包,另一个用于转换字符串。

编辑

这是我的方法。这也不起作用 - 我得到 (NSObject, AnyObject) is not conversionble to String on the 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" )
    }
  }

我的问题中没有它,但除了让这种方式工作之外,我还想拥有

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

最佳答案

您想通过 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.
}

此构造从 userInfo 中安全地提取字符串:

  • 如果 userInfoniluserInfo?["ID"] 返回 nil,因为可选链接条件转换 返回一个String? 类型的变量,其值为nil。然后,可选绑定(bind) 失败,并且未输入该 block 。

  • 如果 "ID" 不是字典中的有效键,userInfo?["ID"] 返回 nil 并且它像前一个案例一样进行。

  • 如果值是另一种类型(如 Int),则条件转换 as? 将返回 nil 和上面的案例一样。

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


对于 Xcode 6.0,您还必须做一件额外的事情。您需要有条件地转换为 NSString 而不是 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.
}

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

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

关于dictionary - 从 userInfo 字典中获取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26331673/

相关文章:

ios - 如何更改键盘的宽度

haskell - 如何减去 Haskell 中的 Maybe 值?例如,如果我想减去 Just 8 - Just 5 得到 Just 3,我该怎么做?

Python MySQLdb "INSERT INTO"问题

python - python中Json格式的两个列表

python - 对 Python 字典列表进行分组

swift - SpriteKit SKAction.animateWithTextures : Resize and Restore

ios - 如何在 Swift 中快速跟踪屏幕 (iOS)

ios - 奇怪的 fatal error : unexpectedly found nil while unwrapping an Optional value

c++ - 如何在没有 if 语句的情况下返回可选的<T>?

c# - 字典通配符搜索