I've looked at the answers for converting int's to floats and other similar answers but they don't do exactly what I want.
I'm trying to create a basic program that takes a number does some different calculations onto it and the results of those calculations are added together at the end.
For one of those calculations I created a segmented controller with the 3 different values below
var myValues: [Double] = [0.00, 1.00, 1.50]
var myValue = [myValuesSegmentedController.selectedSegmentIndex]
then when one of those values is picked, it's added to the final value. All the values added together are Doubles to 2 decimal places.
var totalAmount = valueA + valueB + valueC + myValue
the problem I'm having is that swift won't let me add "myValue" to those final calculations. It gives me the error:
Swift Compiler Error. Cannot invoke '+' with an argument list of type '($T7, @lvalue [int])'
What do I need to do to change that value to a Double? Or what can I do to get a similar result?
double c = a; Here, the int type variable is automatically converted into double . It is because double is a higher data type (data type with larger size) and int is a lower data type (data type with smaller size). Hence, there will be no loss in data while converting from int to double .
Convert Swift String to DoubleUse Double , Float , CGFloat to convert floating-point values (real numbers). let lessPrecisePI = Float("3.14") let morePrecisePI = Double("3.1415926536") let width = CGFloat(Double("200.0")!)
Swift 4.2+ String to Double You should use the new type initializers to convert between String and numeric types (Double, Float, Int). It'll return an Optional type (Double?) which will have the correct value or nil if the String was not a number.
As a result of all this, Swift will refuse to automatically convert between its various numeric types – you can't add an Int and a Double , you can't multiply a Float and an Int , and so on.
You can cast it with Double()
like this
var totalAmount = valueA + valueB + valueC + Double(myValue)
The problem is you are trying to add an array instead of an Int, so You don't even need to convert anything, considering that all of your values are already Doubles and your index actually has to be an Int. So
let myValues = [0.00, 1.00, 1.50]
let myValue = [myValuesSegmentedController.selectedSegmentIndex] // your mistake is here, you are creating one array of integers with only one element(your index)
The correct would be something like these:
let myValues = [0.00, 1.00, 1.50]
let totalAmount = myValues.reduce(0, combine: +) + myValues[myValuesSegmentedController.selectedSegmentIndex]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With