首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何比较NSDictionary和String的值

如何比较NSDictionary和String的值
EN

Stack Overflow用户
提问于 2015-08-26 14:39:39
回答 1查看 483关注 0票数 0

我有两个orgunit_id's,test["orgunit_id"]API.loginManagerInfo.orgUnit,我想比较一下。问题是变量有不同的类型。test["orgunit_id"]NSDictionary的值,另一个是字符串。我尝试过几种方法把它转换成整数,但没有成功。

代码:

代码语言:javascript
复制
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
                ...
        }
    }
}

输出:

代码语言:javascript
复制
[{
    name = Alle;
    "orgunit_id" = "-1";
    shortdescription = Alle;
}, {
    name = "IT-Test";
    "orgunit_id" = 1;
    shortdescription = "";
}]
Optional(-1)
Optional("-1")

编辑:以下是API.loginManagerInfo.orgUnitvar orgUnit:String?的定义

EN

回答 1

Stack Overflow用户

发布于 2015-08-26 14:43:12

使用if let可以安全地打开值并输入结果。

如果test["orgunit_id"]是可选Int,如果API.loginManagerInfo.orgUnit是可选字符串:

代码语言:javascript
复制
if let testID = test["orgunit_id"] as? Int, let apiIDString = API.loginManagerInfo.orgUnit, let apiID =  Int(apiIDString) {
    if testID == apiID {
        // ...
    }    
}

考虑到字典中的内容,您可能不得不修改这个示例,但您明白了一点:安全地打开可选值,并在进行比较之前对其进行类型化(使用if let ... = ... as? ...)或转换它(使用Int(...))。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32229634

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档