Binary operator '??' cannot be applied to

2019-07-27 11:47发布

问题:

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

回答1:

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

For example:

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


回答2:

Do this:

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


回答3:

I ran into the same error with a Date object in Swift 3. The compiler seems to be OK with this:

let noStartDate = "No start date" let description = "(\(self.startDate?.toString() ?? noStartDate)) - \(campaignNotes)"