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

MrX*_*MrX 14 swift

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

/* [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!)
        }
}
Run Code Online (Sandbox Code Playgroud)

错误说:

binary operator cannot be applied to operands of type int and int?
Run Code Online (Sandbox Code Playgroud)

其中:

var filteredCustomReqList: [Any]? /* = [Any]() */
Run Code Online (Sandbox Code Playgroud)

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

任何答案和消化对我都有帮助.提前致谢

Dan*_*ynh 16

您可以使用Optional Binding if let来解包filteredCustomReqListOptional变量.

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!)
    }
}
Run Code Online (Sandbox Code Playgroud)


rma*_*ddy 6

您应该使用可选绑定,因此您没有可选的绑定for.

if let list = filteredCustomReqList {
    for i in 0..<list.count {
    }
}
Run Code Online (Sandbox Code Playgroud)

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

if let list = filteredCustomReqList {
    for tempObj in list {
        bezeichString = tempObj["bezeich"] as! String
    }
}
Run Code Online (Sandbox Code Playgroud)

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

var filteredCustomReqList: [[String: Any]]?
Run Code Online (Sandbox Code Playgroud)

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

  • @Alexander 但 Swift 是专门为避免这种功能而设计的。如果您想要这种行为(“忽略”nils),请使用 Objective-C。 (2认同)

Nic*_*ari 6

这行看起来很可疑:

for i in 0..<filteredCustomReqList?.count {
Run Code Online (Sandbox Code Playgroud)

由于可选链,尤其filteredCustomReqList?.count是类型Int?Int可选)。也就是说,如果数组filteredCustomReqList为非nil,则给出其count属性的值(即,元素数)。但是如果filteredCustomReqListnil,则该传播filteredCustomReqList?.countnil太。

为了同时包含这两种可能性,Swift使用了可选类型Int?(它可以表示有效值Intnil)。它是不等同Int,并因此不能在表达式中使用的expexts 2个IntS(像在你的范围for循环)。

您不能Int?将for循环范围作为上限。这没有意义。您应该在循环之前解开数组:

if let count = filteredCustomReqList?.count {
    // count is of type "Int", not "Int?"
    for i in 0..<count {
        // etc.
Run Code Online (Sandbox Code Playgroud)