Asked Feb 2nd, 5:56 AM 70 0 1
  • 70 0 1
0

Lỗi Phép tính hợp lệ trong Swift 5

Share
  • 70 0 1

Em bị báo lỗi như sau ạ "Binary operator '*' cannot be applied to operands of type 'Double' and 'Double?' ". Em còn mới trong swift hi vọng các anh chị giúp em. Em cảm ơn ạ.

struct ContentView: View {
    @State private var onPeakUsage = ""
    @State private var offPeakUsage = ""
    @State private var midPeakUsage = ""
    
    var onPeakCharges: Double{
        return 0.132 * Double(self.onPeakUsage) ***//Em bị lỗi ơ ̉ đẫy ạ***
    }
    var offPeakCharges: Double{
        return 0.065 * Double(self.offPeakUsage) ***//Em bị lỗi ơ ̉ đẫy ạ***
    }
    var midPeakCharges: Double{
        return 0.094 * Double(self.midPeakUsage) **//Em* bị lỗi ơ ̉ đẫy ạ*
    }
    
    var body: some View {
        
        Form{
            Section(header: Text("Usage Details")){ //Usage Details section
                TextField("On-peak Usage(kWH)", text: $onPeakUsage).keyboardType(.decimalPad)
                TextField("Off-peak Usage(kWH)", text: $offPeakUsage).keyboardType(.decimalPad)
                TextField("Midd-peak Usage(kWH)", text: $midPeakUsage).keyboardType(.decimalPad)
            }
            
            Section(header: Text("Consumption Charges")){ //Consumption Charges section
                TextField("On-peak Charges", text: $onPeakUsage).keyboardType(.decimalPad)
                TextField("Off-peak Charges", text: $offPeakUsage).keyboardType(.decimalPad)
                TextField("Midd-peak Charges", text: $midPeakUsage).keyboardType(.decimalPad)
            }
            
        }
    
    }
}

1 ANSWERS


Answered Feb 2nd, 6:47 PM
Accepted
+2

Lỗi ghi rõ mà bạn hàm Double(self.onPeakUsage) bạn cast string sang double thì có thể none, sài if let để check optional trước nha

Share
Minh Pham @phamduyanminh
Feb 3rd, 4:19 AM

Sau 1 lúc thì mình tìm ra là để nó là (Double(self.onPeakUsage) ?? 0) thì sẽ ko bị lỗi nữa. Cảm ơn bạn.

0
| Reply
Share