DoYouLikeHam
DoYouLikeHam

Reputation: 33

Xcode seems to be confused about the type of parameter required by a function

I have a UIViewController class in which I have this function:

class ViewController: UIViewController {
...
    func DegreesToRadians(degrees: Double) -> Double
    {
        return degrees * .pi / 180.0
    }
...
}

It works just fine within the scope of that class.

However, I'm trying to call this function from within another class

class VoltageVectorsViewController: UIViewController {
...
    func DrawVoltageVector(context: UIGraphicsImageRendererContext, color: CGColor, angleDeg: Double )
    {
...
        /* this is telling me: 
            Cannot convert value of type 'Double' to expected argument type 'ViewController'
        */
        let voltageAngleRadians = ViewController.DegreesToRadians(angleDeg)
...
    }

...
}

See below where Xcode seems to be getting confused as to the parameter types.. what is going on? How do I resolve this?

code completion

enter image description here

Why is it wanting self: ViewController instead of Double as per the func definition?

Upvotes: 1

Views: 52

Answers (1)

vadian
vadian

Reputation: 285079

Xcode is indeed confused because you call an instance method on the class.

A solution is to make the function a class method.

And please name functions/methods with starting lowercase letter

static func degreesToRadians(degrees: Double) -> Double
{
    return degrees * .pi / 180.0
}

Another minor confusion is that the function is actually not related to the view controller with regards to contents.

For example you could create an extra struct for trigonometric functions

struct Trigonometry {
    static func degreesToRadians(degrees: Double) -> Double
    {
        return degrees * .pi / 180.0
    }
}

and call it

let voltageAngleRadians = Trigonometry.degreesToRadians(angleDeg)

Upvotes: 2

Related Questions