我有两个orgunit_id's,test["orgunit_id"]和API.loginManagerInfo.orgUnit,我想比较一下。问题是变量有不同的类型。test["orgunit_id"]是NSDictionary的值,另一个是字符串。我尝试过几种方法把它转换成整数,但没有成功。
代码:
if(!orgUnits.isEmpty){
print(orgUnits) //See at console-output
for test: NSDictionary in orgUnits {
println(test["orgunit_id"]) //See at console-output
println(API.loginManagerInfo.orgUnit) //See at console-output
if(Int(test["orgunit_id"]? as NSNumber) == API.loginManagerInfo.orgUnit?.toInt()){ // This condition fails
...
}
}
}输出:
[{
name = Alle;
"orgunit_id" = "-1";
shortdescription = Alle;
}, {
name = "IT-Test";
"orgunit_id" = 1;
shortdescription = "";
}]
Optional(-1)
Optional("-1")编辑:以下是API.loginManagerInfo.orgUnit:var orgUnit:String?的定义
发布于 2015-08-26 14:43:12
使用if let可以安全地打开值并输入结果。
如果test["orgunit_id"]是可选Int,如果API.loginManagerInfo.orgUnit是可选字符串:
if let testID = test["orgunit_id"] as? Int, let apiIDString = API.loginManagerInfo.orgUnit, let apiID = Int(apiIDString) {
if testID == apiID {
// ...
}
}考虑到字典中的内容,您可能不得不修改这个示例,但您明白了一点:安全地打开可选值,并在进行比较之前对其进行类型化(使用if let ... = ... as? ...)或转换它(使用Int(...))。
https://stackoverflow.com/questions/32229634
复制相似问题