Latcie
Latcie

Reputation: 701

Getting negative of CGVector

I have

let impulse = CGVectorMake(CGFloat(Constants.impulse), 0)

How can I get the negative of it without creating another CGVector?

I was thinking of creating an extension on CGVector to have a method that would reverse it, but I also need it to create a new CGVector, not override impulse.

Also, am I correct in saying that CGVector is a reference type?

Upvotes: 0

Views: 350

Answers (2)

Luca Angeletti
Luca Angeletti

Reputation: 59526

Mutating a struct

You can add a function extension to mutate the var properties inside a struct. The function will need to be marked as mutating.

The code

Here's the code

extension CGVector {
    mutating func negate() {
        dx *= -1
        dy *= -1
    }
}

Example

var impulse = CGVector(dx: 1, dy: 2)
impulse.negate()
print(impulse) // CGVector(dx: -1.0, dy: -2.0)

The second line of code mutated the original impulse value without creating a new value.

Please note that in order to use the negate() mutating function, impulse must be a var.

Upvotes: 0

Alessandro Ornano
Alessandro Ornano

Reputation: 35402

You could extend CGVector methods:

public extension CGVector {
   func horizontalReverse() -> CGVector {
       return CGVector(dx:-self.dx,dy:self.dy)
   }
}

Usage:

var impulse = CGVectorMake(CGFloat(Constants.impulse), 0)
impulse = impulse.horizontalReverse()

In Swift, struct, enum and tuple objects are all value types and objects defined as class are reference types. Value type data is copied when you assign it around whereas reference type data is passed by reference and points to the same underlying data.

Never mind the declaration of CGVector sources. In your case we have let or var declaration.

According to The Swift Programming Language:

Constants and variables must be declared before they are used. You declare constants with the let keyword and variables with the var keyword.

let creates a constant.You can't change its value once you have set it. You can still add it to other things and create new variables though.

var creates a variable. So you can change the value of it.

Upvotes: 1

Related Questions