所以,完全披露:我是 Swift 的新手。
我正在開發一個應用程式,試圖在自定義單元格中獲取標簽以顯示 DOUBLE 值。我試圖做一個 if let 條件系結將它從一個字串轉換為一個雙精度值,但我的源不是一個可選型別,我不能讓它成為可選型別。所以我不確定如何做到這一點。
以下是具體錯誤:
條件系結的初始化程式必須具有可選型別,而不是“雙”
無法分配 “雙”型別的值?輸入“字串?”
呼叫初始化程式時沒有完全匹配
這是代碼:
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
}
提前致謝!
uj5u.com熱心網友回復:
從錯誤中,它看起來像parts[indexPath.row].partCost是已經一個Double-錯誤是告訴你if let只用作業Optional型別。
因此,您可以將if let / else塊替換為:
cell.partCostLabel.text = String(format: "%.2f", parts[indexPath.row].partCost)
cell.partCostLabel.text = 0.00不起作用,因為Text期望String- 您將不再需要上面的代碼,但是處理它的方法是cell.partCostLabel.text = "0.00"
最后,Cannot assign value of type 'Double?' to type 'String?'- 我不確定發生在哪一行,但如果是cell.purchaseDateLabel.text = parts[indexPath.row].purchaseDate 這樣,那就意味著這purchaseDate是 aDouble?并且您正試圖將其設定為期望 a 的內容String。你需要考慮你將如何為轉換Double到一個日期,但這個可能是一個你需要if let:
if let purchaseDate = parts[indexPath.row].purchaseDate {
cell.purchaseDateLabel.text = "\(purchaseDate)" //you probably want a different way to display this, though
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/340170.html
