我是快速的新手,我试了几个小时这个问题。在我的代码下面:
/* [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但它和我的情况不一样(它的int
和CGFloat
)。
任何答案和建议都会对我有所帮助。提前致谢
您可以使用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!)
}
}
您应该使用可选绑定,因此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
值的字典的数组。
这条线看起来很可疑:
for i in 0..<filteredCustomReqList?.count {
特别是,由于可选的链接,filteredCustomReqList?.count
的类型为Int?
(Int
可选)。也就是说,如果数组filteredCustomReqList
是非零的,则给出其count
属性的值(即,其元素的数量)。但如果filteredCustomReqList
是nil
,那就是传播,而filteredCustomReqList?.count
也是nil
。
为了包含两种可能性,Swift使用可选类型Int?
(可以表示有效的Int
值和nil
)。它不等同于Int
,因此不能用于表达两个Int
s的表达式(如for
循环中的范围)。
你不能将Int?
作为你的for循环范围的上限;它没有意义。你应该在循环之前打开数组:
if let count = filteredCustomReqList?.count {
// count is of type "Int", not "Int?"
for i in 0..<count {
// etc.
首先,与其他答案一样,您应该在使用之前解开可选值。
始终牢记,在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)
}