【问题标题】:Get string from userInfo Dictionary从 userInfo 字典中获取字符串
【发布时间】:2014-10-13 01:13:15
【问题描述】:

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

if let s = userInfo?["ID"]

给我一​​个 AnyObject,我必须将其转换为字符串。

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

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

只是不想为了得到一个字符串而声明两个变量——一个用于展开的文字,另一个用于转换后的字符串。

编辑

这是我的方法。这也不起作用 - 我在 if 语句中得到 (NSObject, AnyObject) is not convertible to 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" )
    }
  }

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

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

【问题讨论】:

    标签: dictionary swift optional


    【解决方案1】:

    您想通过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 中提取字符串:

    • 如果userInfonil,则userInfo?["ID"] 由于可选链接而返回nil,并且条件转换返回@类型的变量987654328@,其值为 nil可选绑定然后失败并且没有进入块。

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

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


    对于 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" )
          }
      }
    

    【讨论】:

    • 这不起作用。我发布了我的功能。另外,我在原始问题中没有它,但我最初想从通知中访问 userInfo 。所以 notification.userInfo["ID"].
    • 谢谢。我使用的是 Xcode 6.0.1。升级到 6.1 就可以了。
    • 感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 2023-01-13
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    相关资源
    最近更新 更多