Ted Philip Lat - 4 months ago 40

Objective-C Question

Hi I'm new to swift and OpenGL. I'm following a tutorial in written in objective C and I'm converting it to Swift 2.0

Here is the code

`float radius = self.view.bounds.size.width/3;`

GLKVector3 center = GLKVector3Make(self.view.bounds.size.width/2, self.view.bounds.size.height/2, 0);

GLKVector3 P = GLKVector3Subtract(touchPoint, center);

P = GLKVector3Make(P.x, P.y * -1, P.z);

float radius2 = radius * radius;

float length2 = P.x*P.x + P.y*P.y;

if (length2 <= radius2)

P.z = sqrt(radius2 - length2);

else

{

P.z = radius2 / (2.0 * sqrt(length2));

float length = sqrt(length2 + P.z * P.z);

P = GLKVector3DivideScalar(P, length);

}

Here is my Swift Code

`let radius: CGFloat = self.view.bounds.size.width/3`

let center: GLKVector3 = GLKVector3Make(Float(self.view.bounds.size.width / 2), Float(self.view.bounds.size.height/2), 0.0)

var P: GLKVector3 = GLKVector3Subtract(touchPoint, center)

P = GLKVector3Make(P.x, P.y * -1, P.z)

let radius2 = radius * radius

let length = P.x * P.x + P.y * P.y

if(Float(length) <= Float(radius2)){

P.z = sqrt(Float(radius2) - Float(length)) //the error is here

} else {

//other code

}

I cant change the value of P.z, it says

"Cannot assign property: 'z' is a get-only property"

Thank you in advance

Answer

You need to create a new GLK3DVectorMake. Seems like it is bridged to use Struct in Swift.

Struct are immutable unless they are mutating in the internal implementation. One way to overcome is by creating a new GLK3DVectorMake with correct properties. Its rather a widely used technique for things like modifying CGRect, CGPoint and any struct type.

```
if(Float(length) <= Float(radius2)){
let newz = sqrt(Float(radius2) - Float(length))
P = GLKVector3Make(P.x, P.y * -1, newz)
}
```