早期Swift中Cocos2D初始化代码的重构
我们知道在早期的Swift中在子类里只能调用超类的designated初始化器,这是Swift早期版本的一个限制,所以譬如完成CCSprite子类的init工作,我们就得多写一些代码: init(type:FallingObjectType){
self.type = type
var imageName:String? = nil
if type == .Good{
let rndIndex = randomInteger(FallingObject.imageNames.good.count)
imageName = prefixAssetsPath(FallingObject.imageNames.good[rndIndex])
}else if type == .Bad{
let rndIndex = randomInteger(FallingObject.imageNames.bad.count)
imageName = prefixAssetsPath(FallingObject.imageNames.bad[rndIndex])
}
let spriteFrame = CCSpriteFrame(imageNamed: imageName)
super.init(texture: spriteFrame.texture,rect: spriteFrame.rect,rotated: false)
anchorPoint = ccp(0,0)
}
注意,CCSprite中是有imageNamed: imageName初始化方法的,但该初始化器是一个convenience initializers,So你懂得,我们上面说过子类只能调用超类的非convenience初始化器,所以我们得自己创建一个CCSpriteFrame,然后调用super的init(texture: spriteFrame.texture,rotated: false)初始化器! 不过在最新的Xcode7.3中,版本为2.2的Swift已经不需要这么做了,我们可以直接这么写: init(type:FallingObjectType){
self.type = type
var imageName:String? = nil
if type == .Good{
let rndIndex = randomInteger(FallingObject.imageNames.good.count)
imageName = prefixAssetsPath(FallingObject.imageNames.good[rndIndex])
}else if type == .Bad{
let rndIndex = randomInteger(FallingObject.imageNames.bad.count)
imageName = prefixAssetsPath(FallingObject.imageNames.bad[rndIndex])
super.init(imageNamed: imageName)
anchorPoint = ccp(0,0)
}
直接一个super.init(imageNamed: imageName)搞定了! 但是遗憾的是Swift2.2中还是不支持Type的class属性关键字,只能用static,我们期待Swift3的改进吧! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |