简体   繁体   English

如何在Swift中将Any转换为Int

[英]How to convert Any to Int in Swift

I get an error when declaring i 在宣布我时我收到错误

var users =  Array<Dictionary<String,Any>>()
users.append(["Name":"user1","Age":20])
var i:Int = Int(users[0]["Age"])

How to get the int value? 如何获得int值?

var i = users[0]["Age"] as Int

As GoZoner points out, if you don't know that the downcast will succeed, use: 正如GoZoner所指出的那样,如果你不知道这个垮掉的人会成功,请使用:

var i = users[0]["Age"] as? Int

The result will be nil if it fails 如果失败,结果将nil

Swift 4 answer : 斯威夫特4回答:

if let str = users[0]["Age"] as? String, let i = Int(str) {
  // do what you want with i
}

If you are sure the result is an Int then use: 如果您确定结果是Int那么使用:

var i = users[0]["Age"] as! Int

but if you are unsure and want a nil value if it is not an Int then use: 但是如果你不确定并且想要一个nil值,如果它不是Int那么使用:

var i = users[0]["Age"] as? Int

“Use the optional form of the type cast operator (as?) when you are not sure if the downcast will succeed. “当您不确定向下转换是否成功时,请使用类型转换运算符的可选形式(作为?)。 This form of the operator will always return an optional value, and the value will be nil if the downcast was not possible. 这种形式的运算符将始终返回一个可选值,如果无法进行向下转换,则该值将为nil。 This enables you to check for a successful downcast.” 这使您可以检查成功的向下转发。“

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. 摘录自:Apple Inc.“The Swift Programming Language。”iBooks。 https://itun.es/us/jEUH0.l https://itun.es/us/jEUH0.l

if let id = json["productID"] as? String {
   self.productID = Int32(id, radix: 10)!
}

This worked for me. 这对我有用。 json["productID"] is of type Any . json["productID"]的类型为Any If it can be cast to a string, then convert it to an Integer. 如果它可以转换为字符串,则将其转换为Integer。

This may have worked previously, but it's not the answer for Swift 3. Just to clarify, I don't have the answer for Swift 3, below is my testing using the above answer, and clearly it doesn't work. 这可能以前有效,但它不是Swift 3的答案。只是为了澄清,我没有Swift 3的答案,下面是我使用上述答案的测试,显然它不起作用。

My data comes from an NSDictionary 我的数据来自NSDictionary

print("subvalue[multi] = \(subvalue["multi"]!)")
print("as Int = \(subvalue["multi"]! as? Int)")
if let multiString = subvalue["multi"] as? String {
  print("as String = \(multiString)")
  print("as Int = \(Int(multiString)!)")
}

The output generated is: 生成的输出是:

subvalue[multi] = 1
as Int = nil

Just to spell it out: 只是拼出来:
a) The original value is of type Any? a)原始值是否为Any? and the value is: 1 价值是:1
b) Casting to Int results in nil b)转换为Int结果为零
c) Casting to String results in nil (the print lines never execute) c)Casting to String导致nil(打印行永不执行)

EDIT 编辑
The answer is to use NSNumber 答案是使用NSNumber
let num = subvalue["multi"] as? 让num = subvalue [“multi”]为? NSNumber 的NSNumber

Then we can convert the number to an integer 然后我们可以将数字转换为整数
let myint = num.intValue 让myint = num.intValue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM