Math divison in Swift

Solution 1:

Your code is performing integer division, taking the integer result and converting it to a double. Instead, you want to convert these individual integers to doubles and then do the division. So, instead of

let result = (Double(myInt! / lutning) * Double(pi))

You should

let result = Double(myInt!) / Double(lutning) * Double(pi)

Note, Double already has a .pi constant, so you can remove your pi constant, and simplify the above to:

let result = Double(myInt!) / Double(lutning) * .pi

Personally, I’d define myInt and lutning to be Double from the get go (and, while we’re at it, remove all of the forced unwrapping (with the !) of the optionals):

guard
    let text = graderna.text,
    let text2 = radien.text,
    let value = Double(text),
    let value2 = Double(text2)
else {
    return
}

let lutning: Double = 360
let result = value / lutning * .pi

Or, you can use flatMap to safely unwrap those optional strings:

guard
    let value = graderna.text.flatMap({ Double($0) }),
    let value2 = radien.text.flatMap({ Double($0) })
else {
    return
}

let lutning: Double = 360
let result = value / lutning * .pi

(By the way, if you’re converting between radians and degrees, it should be 2π/360, not π/360.)

Solution 2:

You are dividing an Int by an Int.

Integer division rounds to the nearest integer towards zero. Therefore for example 359 / 360 is not a number close to 1, it is 0. 360 / 360 up to 719 / 360 equals 1. 720 / 360 to 1079 / 360 equals 2, and so on.

But your use of optionals is atrocious. I'd write

let myInt = Int(graderna.text!)
let myInt2 = Int(radien.text!)

if let realInt = myInt, realInt2 = myInt2 {
    let pi = 3.1415926
    let lutning = 360.0

    let result = Double (realInt) * (pi / lutning)
    svar2.text = "\(result)"
}