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

微笑、不失礼 提交于 2019-12-24 09:03:05

问题


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)"



来源:https://stackoverflow.com/questions/39871583/binary-operator-cannot-be-applied-to-operands-of-type-anyobject-and-str

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!