Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary operator cannot be applied to operands of type int and int? Swift 3

Tags:

swift

I'm new in swift and I've try this problem for a couple hour. Below my code :

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

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

the error say :

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

where :

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

if i using var filteredCustomReqList: [Any] = [Any]() the error is gone but my if condition is always true. How to get this fix ? I have read this but its not same with my case (its int and CGFloat) .

Any answer and sugestion will help for me. Thanks In Advance

like image 995
MrX Avatar asked Apr 13 '17 02:04

MrX


2 Answers

You should use optional binding so you don't have an optional in the for line.

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

Even better would be to use a better for loop:

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

But to do this, declare filteredCustomReqList properly:

var filteredCustomReqList: [[String: Any]]?

This makes it an array that contains dictionaries that have String keys and Any values.

like image 36
rmaddy Avatar answered Sep 30 '22 00:09

rmaddy


You can use Optional Binding if let to unwrap filteredCustomReqList Optional variable.

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!)
    }
}
like image 104
Danh Huynh Avatar answered Sep 30 '22 01:09

Danh Huynh