So, full disclosure: I'm a newbie to Swift.
I'm working on an app, trying to get a label in a custom cell to display a DOUBLE value. I've tried to do an if let conditional binding to cast it from a string to a double, but my source isn't an optional type, and I can't make it optional. So I'm not sure how to do this.
Here are the specific errors:
initializer for conditional binding must have Optional type, not 'Double'
Cannot assign value of type 'Double?' to type 'String?'
No exact matches in call to initializer
and here's the code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DemoTableViewCell", for: indexPath) as! DemoTableViewCell
cell.partNameLabel.text = parts[indexPath.row].partName
// Convert string value to double
if let value = parts[indexPath.row].partCost {
cell.partCostLabel.text = Double(value)
} else {
cell.partCostLabel.text = 0.00
}
cell.purchaseDateLabel.text = parts[indexPath.row].purchaseDate
return cell
}
Thanks in advance!
CodePudding user response:
you tried to assign double to string, in here you need the conversion of double (yourvalue) to string(cell.partCostLabel.text) using String(format:), foe e.g,
initializer for conditional binding must have Optional type, not 'Double' Cannot assign value of type 'Double?' to type 'String?' No exact matches in call to initializer
Ans :
cell.partCostLabel.text = "0.00"
if let value = parts[indexPath.row].partCost {
cell.partCostLabel.text = String(format: "%.2f", Double(value))
}
for more info : Swift double to string
CodePudding user response:
From the error, it looks like parts[indexPath.row].partCost
is already a Double
-- the error is telling you if let
only works with Optional
types.
So, you can replace your if let / else
block with:
cell.partCostLabel.text = String(format: "%.2f", parts[indexPath.row].partCost)
cell.partCostLabel.text = 0.00
doesn't work because Text
expects a String
-- you won't need this anymore with the above code, but the way to handle it would be cell.partCostLabel.text = "0.00"
Finally, Cannot assign value of type 'Double?' to type 'String?'
-- I'm not sure what line that's occurring on, but if it's cell.purchaseDateLabel.text = parts[indexPath.row].purchaseDate
then that means that purchaseDate
is a Double?
and you're trying to set it to something that expects a String
. You will need to consider how you're going to convert a Double
to a date, but this one might be the one where you need if let
:
if let purchaseDate = parts[indexPath.row].purchaseDate {
cell.purchaseDateLabel.text = "\(purchaseDate)" //you probably want a different way to display this, though
}