大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;)
我们知道在早期的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, rect: spriteFrame.rect, 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的改进吧!