Nijar Nijar - 1 month ago 16
Swift Question

Binary operator '??' cannot be applied to operands of type 'AnyObject?' and 'String'

I have done below code with Swift 2.2, but when switched to Swift 3.0 getting error at if condition "Binary operator '??' cannot be applied to operands of type 'AnyObject?' and 'String'"

if let custID = dataDict["cust_id"] ?? "",
let custName = dataDict["cust_name"] ?? "",
let fileName = dataDict["filename"] ?? "",
let transNumber = dataDict["trans_no"] ?? "" {

linesheet_custID = (custID["text"] ?? "" ) as! String
linesheet_custName = (custName["text"] ?? "" ) as! String
linesheet_filename = (fileName["text"] ?? "" ) as! String
linesheet_TransNumber = (transNumber["text"] ?? "" ) as! String
}


Please suggest solution ,as in above code in if let statement if dictionary value returns nil then i assigned blank string as ("") for particular key

Answer

You should cast the values you get from the dictionaries to optional Strings.

For example:

let custID = (dataDict["cust_id"] as String?) ?? ""