[英]How to convert Any to Int in swift?
Before asking this question I have searched the Stackoverflow's related questions, and found a similar one: How to convert Any to Int in Swift . 在提出这个问题之前,我已经搜索了Stackoverflow的相关问题,并找到了类似的问题: 如何在Swift中将Any转换为Int 。
My requirement is not that less: 我的要求不是那么少:
let tResult = result as? [String:AnyObject]
let stateCode = tResult?["result"] as? Int
My need is if the tResult?["result"]
is a String
class, I want it to be convert to Int
too, rather than to nil
. 我的需要是如果
tResult?["result"]
是一个String
类,我希望它也可以转换为Int
,而不是nil
。
In objective-c
, I wrote a class method
to get the converted Int
: 在
objective-c
,我编写了一个class method
来获取转换后的Int
:
+ (NSInteger)getIntegerFromIdValue:(id)value
{
NSString *strValue;
NSInteger ret = 0;
if(value != nil){
strValue = [NSString stringWithFormat:@"%@", value];
if(![strValue isEqualToString:@""] && ![strValue isEqualToString:@"null"]){
ret = [strValue intValue];
}
}
return ret;
}
Is it possible to write a similar class method
using Swift3? 是否可以使用Swift3编写类似的
class method
?
Less verbose answer: 不那么冗长的答案:
let key = "result"
let stateCode = tResult?[key] as? Int ?? Int(tResult?[key] as? String ?? "")
Results: 结果:
let tResult: [String: Any]? = ["result": 123] // stateCode: 123
let tResult: [String: Any]? = ["result": "123"] // stateCode: 123
let tResult: [String: Any]? = ["result": "abc"] // stateCode: nil
if
let tResult = result as? [String:AnyObject],
let stateCodeString = tResult["result"] as? String,
let stateCode = Int(stateCodeString)
{
// do something with your stateCode
}
And you don't need any own class methods
. 而且你不需要任何自己的
class methods
。
if let stateCode = tResult["result"] as? String {
if let stateCodeInt = Int(stateCode){
// stateCodeInt is Int
}
}else if let stateCodeInt = tResult["result"] as? Int {
// stateCodeInt is Int
}
Something like this should work 这样的事情应该有效
Try This 试试这个
class func getIntegerFromIdValue(_ value: Any) -> Int {
var strValue: String
var ret = 0
if value != nil {
strValue = "\(value)"
if !(strValue == "") && !(strValue == "null") {
ret = Int((strValue as NSString ?? "0").intValue)
}
}
return ret
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.