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

时间:2017-04-13 02:54:55

标签: swift

我是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!)
        }
}

错误说:

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

其中:

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

如果我使用var filteredCustomReqList: [Any] = [Any]()错误消失但我的if条件总是为真。如何解决这个问题?我看过this,但与我的案例不一致(intCGFloat)。

任何答案和消息对我都有帮助。在此先感谢

4 个答案:

答案 0 :(得分:14)

您可以使用Optional Binding RoutedEventHandler tempEventHandler = this.MyRoutedEventhander; public void MyRoutedEventHandler(object sender, RoutedEventArgs arguments) { _tcs.TrySetResult(null); } 来解包if let可选变量。

filteredCustomReqList

答案 1 :(得分: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值的字典的数组。

答案 2 :(得分:4)

这一行看起来很可疑:

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

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

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

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

Int?

答案 3 :(得分:3)

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

始终牢记,快速不要将可选值视为一种特殊类型的价值本身。它们完全不同。

一个可选&lt; 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)
}