我是快速的新手,我试了几个小时这个问题.在我的代码下面:
/* [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条件总是如此.如何解决这个问题?我已经读过这个,但它与我的情况(它int
和CGFloat
)不一样.
任何答案和消化对我都有帮助.提前致谢
Dan*_*ynh 16
您可以使用Optional Binding if let
来解包filteredCustomReqList
Optional变量.
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)
您应该使用可选绑定,因此您没有可选的绑定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
值的字典的数组.
这行看起来很可疑:
for i in 0..<filteredCustomReqList?.count {
Run Code Online (Sandbox Code Playgroud)
由于可选链,尤其filteredCustomReqList?.count
是类型Int?
(Int
可选)。也就是说,如果数组filteredCustomReqList
为非nil,则给出其count
属性的值(即,元素数)。但是如果filteredCustomReqList
是nil
,则该传播filteredCustomReqList?.count
是nil
太。
为了同时包含这两种可能性,Swift使用了可选类型Int?
(它可以表示有效值Int
和nil
)。它是不等同于Int
,并因此不能在表达式中使用的expexts 2个Int
S(像在你的范围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)