objective-c - Swift - 如何更改仅获取属性的值

标签 objective-c swift xcode opengl swift2

嗨,我是 swift 和 OpenGL 的新手。我正在遵循用 Objective C 编写的教程,并将其转换为 Swift 2.0

这是代码

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);
}

这是我的 Swift 代码

    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
    }

我无法更改 P.z 的值,它说

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

提前谢谢

最佳答案

您需要创建一个新的 GLK3DVectorMake。似乎它被桥接到 Swift 中使用 Struct 。

结构体是不可变的,除非它们在内部实现中发生变化。解决方法之一是创建具有正确属性的新 GLK3DVectorMake。它是一种广泛使用的技术,用于修改 CGRect、CGPoint 和任何结构类型等。

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

关于objective-c - Swift - 如何更改仅获取属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39543886/

相关文章:

ios - NSData 长度 - 隐式转换会丢失整数精度

ios - xcode 5.1 不断修改我的 Storyboard

xcode - Xcode 的复杂表达式

objective-c - NSClassFromString() 安全问题

iphone - 使用 KVC/valueForKey 与属性访问 NSManagedObject 字段 - 哪个更好?

objective-c - Sqlite3 表主键被替换

swift - 用一个按钮链接两个选择器,一个结果 swift

xcode - DatePicker 本地通知(Xcode,swift2)

ios - Swift 如何修改从手机相机拍摄的图像中的 exif 信息

ios - 在 Xcode 9 上运行在 Xcode 8 中创建的项目