Ios 如何将NSDictionary的值与字符串进行比较
我有两个Ios 如何将NSDictionary的值与字符串进行比较,ios,swift,nsdictionary,Ios,Swift,Nsdictionary,我有两个orgunit\u id,test[“orgunit\u id”]和API.loginManagerInfo.orgunit,我想对它们进行比较。问题是变量有不同的类型测试[“orgunit\u id”]是NSDictionary的值,另一个是字符串。 我尝试了几种方法将其转换为整数,但没有成功 代码: if(!orgUnits.isEmpty){ print(orgUnits) //See at console-output for test: NSDictionar
orgunit\u id
,test[“orgunit\u id”]
和API.loginManagerInfo.orgunit
,我想对它们进行比较。问题是变量有不同的类型<代码>测试[“orgunit\u 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")
输出:
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?
如果让安全地打开值并键入结果,请使用
如果test[“orgunit\u 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 {
// ...
}
}
考虑到字典中的内容,您可能需要修改此示例,但您得到了要点:安全地打开可选值,然后在比较之前键入它(如果让…=…as?…
),或者转换它(使用Int(…)
)。感谢您的快速回复。我得到了以下编译错误:带有getter/setter的变量不能有初始值
好的,这会带来更多错误消息。第一:“let”不能嵌套在另一个“var”或“let”模式中
,第二:变量在其自身初始值中使用
。在我的示例中,var
中没有嵌套的let
。这个错误来自于代码中我们不知道的特定内容。此外,请确保至少使用Swift 1.2,而不是旧版本!否则,多个if let
将无法正常工作。