簡體   English   中英

從userInfo Dictionary獲取字符串

[英]Get string from userInfo Dictionary

我有來自UILocalNotification的userInfo字典。 使用隱式展開時是否有一種簡單的方法來獲取String值?

if let s = userInfo?["ID"]

給我一個AnyObject,我必須強制轉換為字符串。

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

給我一個關於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" )
    }
  }

我沒有在我的問題中,但除了這種方式工作,我想真的有

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

你想使用as?使用條件 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?類型的變量String? 它的值nil 然后, 可選綁定失敗,並且未輸入塊。

  • 如果"ID"不是字典中的有效密鑰,則userInfo?["ID"]返回nil並且它像前一種情況一樣繼續。

  • 如果值是另一種類型(如Int ),則條件轉換 as? 將返回nil ,並像上述情況一樣繼續。

  • 最后,如果userInfo不是nil ,並且"ID"是字典中的有效鍵,並且值的類型是String ,則條件轉換返回可選字符串String? 包含字符串。 可選綁定 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" )
      }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM