I have two orgunit_id
's, test["orgunit_id"]
and API.loginManagerInfo.orgUnit
, which I would like to compare. The problem is that the variables have different types. test["orgunit_id"]
is value of a NSDictionary
and the other one is a String. I've tried several ways to cast it into Integers, but without success.
我有两个orgunit_id,test [“orgunit_id”]和API.loginManagerInfo.orgUnit,我想比较一下。问题是变量有不同的类型。 test [“orgunit_id”]是NSDictionary的值,另一个是String。我已经尝试了几种方法将它转换为Integers,但没有成功。
Code:
码:
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
...
}
}
}
Output:
输出:
[{
name = Alle;
"orgunit_id" = "-1";
shortdescription = Alle;
}, {
name = "IT-Test";
"orgunit_id" = 1;
shortdescription = "";
}]
Optional(-1)
Optional("-1")
Edit: Here's the definition of API.loginManagerInfo.orgUnit
: var orgUnit:String?
编辑:这是API.loginManagerInfo.orgUnit的定义:var orgUnit:String?
1 个解决方案
#1
0
Use if let
to safely unwrap your values and typecast the result.
如果让我们安全地展开您的值并对结果进行类型转换,请使用。
If test["orgunit_id"]
is an Optional Int and if API.loginManagerInfo.orgUnit
is an Optional String:
如果test [“orgunit_id”]是一个Optional Int,并且API.loginManagerInfo.orgUnit是一个可选字符串:
if let testID = test["orgunit_id"] as? Int, let apiIDString = API.loginManagerInfo.orgUnit, let apiID = Int(apiIDString) {
if testID == apiID {
// ...
}
}
You may have to adapt this example given what is in your dictionary, but you get the point: safely unwrap the optional value and either typecast it (with if let ... = ... as? ...
) or transform it (with Int(...)
) before comparing.
您可能必须根据字典中的内容调整此示例,但您明白了这一点:安全地展开可选值并对其进行类型转换(如果让... = ...作为?...)或对其进行转换(与Int(...))比较之前。
#1
0
Use if let
to safely unwrap your values and typecast the result.
如果让我们安全地展开您的值并对结果进行类型转换,请使用。
If test["orgunit_id"]
is an Optional Int and if API.loginManagerInfo.orgUnit
is an Optional String:
如果test [“orgunit_id”]是一个Optional Int,并且API.loginManagerInfo.orgUnit是一个可选字符串:
if let testID = test["orgunit_id"] as? Int, let apiIDString = API.loginManagerInfo.orgUnit, let apiID = Int(apiIDString) {
if testID == apiID {
// ...
}
}
You may have to adapt this example given what is in your dictionary, but you get the point: safely unwrap the optional value and either typecast it (with if let ... = ... as? ...
) or transform it (with Int(...)
) before comparing.
您可能必须根据字典中的内容调整此示例,但您明白了这一点:安全地展开可选值并对其进行类型转换(如果让... = ...作为?...)或对其进行转换(与Int(...))比较之前。