Search code examples
swiftxcodevariablesrandomangle

Swift-Binary operator cannot be applied to operands, when converting degrees to radians


I'm aware of some relatively similar questions on this site, but if they do apply to my problem (which I'm not certain they do) then I certainly don't understand them. Here's my problem;

var degrees = UInt32()
var radians = Double()

let degrees:UInt32 = arc4random_uniform(360)
let radians = angle * (M_PI / 180)

This returns an error, focused on the multiplication star, reading; "Binary operator "*" cannot be applied to operands of type 'UInt32' and 'Double'.

I'm fairly sure I need to have the degrees variable be of type UInt32 to randomise it, and also that the pi constant cannot be made to be of UInt32, or at least I don't know how, as I'm relatively new to Xcode and Swift in general.

I'd be very grateful if anyone had a solution to my problem.

Thanks in advance.


Solution

  • let degree = arc4random_uniform(360)
    
    let radian = Double(degree) * .pi/180
    

    you need to convert the degree to double before the multiplication .

    from apple swift book:

    Integer and Floating-Point Conversion

    Conversions between integer and floating-point numeric types must be made explicit:

    let three = 3
    let pointOneFourOneFiveNine = 0.14159
    let pi = Double(three) + pointOneFourOneFiveNine
    

    // pi equals 3.14159, and is inferred to be of type Double

    Here, the value of the constant three is used to create a new value of type Double, so that both sides of the addition are of the same type. Without this conversion in place, the addition would not be allowed. Floating-point to integer conversion must also be made explicit. An integer type can be initialized with a Double or Float value:

    1 let integerPi = Int(pi)
    2 // integerPi equals 3, and is inferred to be of type Int
    

    Floating-point values are always truncated when used to initialize a new integer value in this way. This means that 4.75 becomes 4, and -3.9 becomes -3.