[英]How to convert Any to Int in swift?
在提出这个问题之前,我已经搜索了Stackoverflow的相关问题,并找到了类似的问题: 如何在Swift中将Any转换为Int 。
我的要求不是那么少:
let tResult = result as? [String:AnyObject]
let stateCode = tResult?["result"] as? Int
我的需要是如果tResult?["result"]
是一个String
类,我希望它也可以转换为Int
,而不是nil
。
在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;
}
是否可以使用Swift3编写类似的class method
?
不那么冗长的答案:
let key = "result"
let stateCode = tResult?[key] as? Int ?? Int(tResult?[key] as? String ?? "")
结果:
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
}
而且你不需要任何自己的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
}
这样的事情应该有效
试试这个
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.