What is the Swift alternative of radiansToVector and randomInRange Objective-C functions?

| | August 5, 2015

I watched an old ios 7 spritekit course and they use these methods. I tried to use them in Swift, but they didn’t work. What should I use instead?

static inline CGVector radiansToVector(CGFloat radians) {
    CGVector vector;
    vector.dx = cosf(radians);
    vector.dy = sinf(radians);
    return vector;
}

static inline CGFloat randomInRange(CGFloat low, CGFloat high) {
    CGFloat value = arc4random_uniform(UINT32_MAX) / (CGFloat)UINT32_MAX;
    return value * (high - low) + low;
}

One Response to “What is the Swift alternative of radiansToVector and randomInRange Objective-C functions?”

  1. Swift re-write:

    func randomInRange(low: CGFloat, high: CGFloat) -> CGFloat {
        let value = CGFloat(arc4random_uniform(UINT32_MAX)) / CGFloat(UINT32_MAX)
        return value * (high - low) + low
    }
    
    func radiansToVector(radians: CGFloat) -> CGVector {
        return CGVector(dx: cos(radians), dy: sin(radians))
    }
    

    UPDATE: More swiftish way of the latter (thanks to @Jessy for pointing out):

    extension CGVector {
        init(radians: CGFloat) {
            self.dx = cos(radians)
            self.dy = sin(radians)
        }
    }
    

Leave a Reply