简体   繁体   中英

How do you convert int to double in swift?

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()来强制转换它

var totalAmount = valueA + valueB + valueC + Double(myValue)

Put this in a playground:

var myValues: [Double] = [0.00, 1.00, 1.50]
let valueA = 1
let valueB = 2
let valueC = 3
var totalAmount = Double(valueA + valueB + valueC) + myValues[2]
println(totalAmount)  //output is 7.5

valueA/B/C are all inferred to be Int.

totalAmount is inferred to be a Double

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]

To convert a float to an integer in Swift . Basic casting like this does not work because these vars are not primitives, unlike floats and ints in Objective-C :

var float:Float = 2.2
var integer:Int = float as Float

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM