二进制运算符不能应用于int和int类型的操作数?斯威夫特3

问题描述 投票:13回答:4

我是快速的新手,我试了几个小时这个问题。在我的代码下面:

/* [1] error in this line */if filteredCustomReqList != nil {
        for i in 0..<filteredCustomReqList?.count {
            tempObj = filteredCustomReqList[i] as! [AnyHashable: Any]
            bezeichString = tempObj?["bezeich"] as! String


            specialRequestLabel.text = ("\(filteredString), \(bezeichString!)")
            print (bezeichString!)
        }
}

错误说:

binary operator cannot be applied to operands of type int and int?

其中:

var filteredCustomReqList: [Any]? /* = [Any]() */

如果我使用var filteredCustomReqList: [Any] = [Any]()错误消失但我的if条件总是如此。如何解决这个问题?我读过this但它和我的情况不一样(它的intCGFloat)。

任何答案和建议都会对我有所帮助。提前致谢

swift
4个回答
14
投票

您可以使用Optional Binding if let来解包filteredCustomReqList可选变量。

var filteredCustomReqList: [Any]?

if let filteredCustomReqList = filteredCustomReqList {
    for i in 0..<filteredCustomReqList.count {
        tempObj = filteredCustomReqList[i] as! [AnyHashable: Any]
        bezeichString = tempObj?["bezeich"] as! String

        specialRequestLabel.text = ("\(filteredString), \(bezeichString!)")
        print (bezeichString!)
    }
}

6
投票

您应该使用可选绑定,因此for行中没有可选项。

if let list = filteredCustomReqList {
    for i in 0..<list.count {
    }
}

更好的是使用更好的for循环:

if let list = filteredCustomReqList {
    for tempObj in list {
        bezeichString = tempObj["bezeich"] as! String
    }
}

但要做到这一点,请正确声明filteredCustomReqList

var filteredCustomReqList: [[String: Any]]?

这使得它成为一个包含具有String键和Any值的字典的数组。


4
投票

这条线看起来很可疑:

for i in 0..<filteredCustomReqList?.count {

特别是,由于可选的链接,filteredCustomReqList?.count的类型为Int?Int可选)。也就是说,如果数组filteredCustomReqList是非零的,则给出其count属性的值(即,其元素的数量)。但如果filteredCustomReqListnil,那就是传播,而filteredCustomReqList?.count也是nil

为了包含两种可能性,Swift使用可选类型Int?(可以表示有效的Int值和nil)。它不等同于Int,因此不能用于表达两个Ints的表达式(如for循环中的范围)。

你不能将Int?作为你的for循环范围的上限;它没有意义。你应该在循环之前打开数组:

if let count = filteredCustomReqList?.count {
    // count is of type "Int", not "Int?"
    for i in 0..<count {
        // etc.

3
投票

首先,与其他答案一样,您应该在使用之前解开可选值。

始终牢记,在swift中不要将可选值仅视为值本身的特殊类型。它们完全不同。

Optional <T>是Optional的结构,如果它存在,则将T的值关联起来,它看起来是:

enum Optional< T > {
    case NIL
    case SOME(T)
}

实际上,在Swift中你可以更好地做到以上几点:

// if you don't need return any thing you can just use forEach
filteredCustomerReqList?.map { obj in 
    tempObj = obj as? [AnyHashable: Any]
    bezeichString = tempObj?["bezeich"] as? String
    specialRequestLabel.text = ("\(filteredString),\(bezeichString)")
    print(bezeichString)
}
© www.soinside.com 2019 - 2024. All rights reserved.