将Objective-C的Transformations类转换为Swift 3的技术求助
把Objective-C的Transformations类完整转换为Swift 3
你在实现基础UIGestureRecognizer控件时,遇到了将Objective-C的Transformations类转换为Swift 3的难题,我来帮你梳理问题并完成正确的转换,同时验证你当前代码的问题点。
原Objective-C代码
头文件(Transformations.h)
@interface Transformations : NSObject - (id)initWithDepth:(float)z Scale:(float)s Translation:(GLKVector2)t Rotation:(GLKVector3)r; - (void)start; - (void)scale:(float)s; - (void)translate:(GLKVector2)t withMultiplier:(float)m; - (void)rotate:(GLKVector3)r withMultiplier:(float)m; - (GLKMatrix4)getModelViewMatrix; @end
实现文件(Transformations.m)
#import "Transformations.h" @interface Transformations () { // Depth float _depth; } @end @implementation Transformations - (id)initWithDepth:(float)z Scale:(float)s Translation:(GLKVector2)t Rotation:(GLKVector3)r { if(self = [super init]) { _depth = z; } return self; } - (void)start { } - (void)scale:(float)s { } - (void)translate:(GLKVector2)t withMultiplier:(float)m { } - (void)rotate:(GLKVector3)r withMultiplier:(float)m { } - (GLKMatrix4)getModelViewMatrix { GLKMatrix4 modelViewMatrix = GLKMatrix4Identity; modelViewMatrix = GLKMatrix4Translate(modelViewMatrix, 0.0f, 0.0f, -_depth); return modelViewMatrix; } @end
你当前Swift代码的问题
你写的Swift代码存在几个关键错误:
- 把实例方法定义在了
init内部,这会导致这些方法变成初始化方法的局部函数,外部完全无法调用,不符合原OC类的接口设计 - 缺失了原OC类的核心私有成员
_depth,这是getModelViewMatrix方法的依赖属性 - 初始化方法参数不全,原OC的初始化方法包含
depth、scale、translation、rotation四个参数,你漏了depth - 没有实现
start()和getModelViewMatrix()两个关键方法
完整的Swift 3转换代码
import GLKit class Transformations: NSObject { // 对应OC的私有成员_depth,Swift中用私有属性封装 private var depth: Float // 保留OC初始化方法传入的其他参数,方便后续扩展逻辑 private var initialScale: Float private var initialTranslation: GLKVector2 private var initialRotation: GLKVector3 init(depth z: Float, scale s: Float, translation t: GLKVector2, rotation r: GLKVector3) { self.depth = z self.initialScale = s self.initialTranslation = t self.initialRotation = r super.init() } func start() { // 原OC空实现,可根据需求添加逻辑 } func scale(_ s: Float) { // 原OC空实现,可根据需求添加逻辑 } func translate(_ t: GLKVector2, withMultiplier m: Float) { // 原OC空实现,可根据需求添加逻辑 } func rotate(_ r: GLKVector3, withMultiplier m: Float) { // 原OC空实现,可根据需求添加逻辑 } func getModelViewMatrix() -> GLKMatrix4 { var modelViewMatrix = GLKMatrix4Identity modelViewMatrix = GLKMatrix4Translate(modelViewMatrix, 0.0, 0.0, -depth) return modelViewMatrix } }
转换说明
- 属性处理:将OC的私有成员
_depth转换为Swift的私有属性private var depth: Float,同时保留了初始化方法传入的其他参数作为属性,方便后续扩展业务逻辑 - 初始化方法:遵循Swift初始化规则,先为所有存储属性赋值,再调用
super.init(),参数命名采用Swift小驼峰规范,同时用外部参数名对应OC的参数命名习惯 - 方法转换:
- OC的无返回值方法直接转换为Swift的
func - 方法参数用
_省略外部参数名,符合Swift 3的语法风格 - 完全复刻了
getModelViewMatrix()的OC逻辑,调用GLKit的GLKMatrix4Translate生成矩阵
- OC的无返回值方法直接转换为Swift的
- 框架导入:Swift中需要显式导入
GLKit框架,才能使用GLKVector2、GLKVector3、GLKMatrix4等类型
内容的提问来源于stack exchange,提问作者E. Huckabee
相关产品推荐
相关产品推荐

