'Two Problems in Swift
I am new to programming and I am making my first app in xcode. I keep getting these 2 errors with little to no information on them on the internet. They are as follows:
Binary operator '*' cannot be applied to operands type '_' and 'String'"
Binary operator '*' cannot be applied to two 'String' operands.
This is the code I have for it.
@IBAction func Calculate(_ sender: UIButton){
// V_1 = (M_3V_2-M_2V_2)/(M_1-M_3)
var a = CurrentPH.text
var b = TargetPH.text
var c = WaterVolume.text
var d = PHDownn.text
var Answer = b! * c! - a! * c! / d! - b!
Answer = PHOutput.text
}
}
Solution 1:[1]
Read about binary operators, they need 2 operands to work with. Such as multiplication.
You cannot apply * (multiplication) on two strings.
The first error says that You cannot multiply [anything] with String and the second that you cannot multiply 2 strings together.
It's not clear from your question what are you trying to do.
Solution 2:[2]
Adding to what @DeepBlue is saying, I believe what you are trying to do, is to calculate with the values from text fields and place the answer in a fifth text field, when you press a button.
That would look something like this
@IBAction func Calculate(_ sender: UIButton){
// V_1 = (M_3V_2-M_2V_2)/(M_1-M_3)
let a = Int(CurrentPH.text!)!
let b = Int(TargetPH.text!)!
let c = Int(WaterVolume.text!)!
let d = Int(PHDownn.text!)!
let answer = b * c - a * c / d - b
PHOutput.text = String(answer)
}
}
Since none of the variables are modified, I'm using let instead which makes them constants.
Since converting a String to an Int can fail, for example if you type text into the text fields, it can result in a nil result. To simplify the formula the integer conversion is force unwrapped.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DeepBlue |
| Solution 2 | TimTwoToes |
