1

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

Nijar
  • 81
  • 1
  • 9

3 Answers3

4

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

For example:

let custID = (dataDict["cust_id"] as String?) ?? ""
Max Pevsner
  • 4,098
  • 2
  • 18
  • 32
0

Do this:

let custID = dataDict["cust_id"] as? String ?? ""
pixelfreak
  • 17,714
  • 12
  • 90
  • 109
0

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

Matt Bearson
  • 993
  • 8
  • 15