【问题标题】:NSDictionary returning an optional integer when retrieving informationNSDictionary 在检索信息时返回一个可选整数
【发布时间】:2015-03-20 01:43:28
【问题描述】:

我有这样声明的字典:

var friendLetterCount:NSDictionary = NSDictionary(dictionary: [String:Int]())

我显然想检索字典中键的信息,但是当我这样做时,它只返回可选整数,我该如何使它们成为整数?

我这样检索:

friendLetterCount["a"]

当我将它打印到控制台时,它会说

optional(1)

我已经尝试以我能想象到的所有方式对其进行转换,但它总是给我一个错误提示

'(NSObject, AnyObject)' is not convertible to 'Int'

任何建议将不胜感激。

【问题讨论】:

  • 这几乎是 stackoverflow.com/questions/25979969/… 的副本(仅使用 NSDictionary 而不是 Dictionary)。 – Optional 是 Swift 语言的一个关键概念,你真的应该阅读文档并学习如何处理它们。

标签: swift dictionary int type-conversion nsdictionary


【解决方案1】:

Optional(1) 值仅表示该值是可选的 swift 类型。

您可以使用 ! 运算符从可选项中解开值。

let a = friendLetterCount["a"]! as Int
println(a)

a 将解包的值。

您还可以使用optional binding 在解包的同时检查 nil。

if let a = friendLetterCount["a"] as? Int
{
    println(a)
}

请从 Apple 的 Swift Book 中了解 Optionals。

你也可以阅读这样的文章 http://www.appcoda.com/beginners-guide-optionals-swift/

【讨论】:

  • 最好使用as? Int而不是as Int?,否则如果值存在但不是整数会崩溃。
【解决方案2】:
class AppModel: NSObject {

private  var _user_id:String?

final func serviceResult(results:NSObject) {

var data = results as? NSDictionary
_user_id = String (data?.objectForKey("userId") as! Int)
 println("user id \(_user_id)")

}

}

Note: AppMOdel is a NSObject class, results is the parsed JSON DATA, data- NSDictionary, _user_id is a private variable.

It return the print as : 

user id Optional("8")

【讨论】:

    【解决方案3】:

    如果您不确定该值是否始终为 Integer(通常使用 String/Intger 发生这种情况),最安全的方法是:

    if let count = friendLetterCount["a"]?.integerValue  {
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      • 2011-12-01
      • 1970-01-01
      • 2013-08-09
      • 1970-01-01
      • 1970-01-01
      • 2020-09-01
      相关资源
      最近更新 更多