加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

早期Swift中Cocos2D初始化代码的重构

发布时间:2020-12-14 07:06:04 所属栏目:百科 来源:网络整理
导读:大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 我们知道在早期的Swift中在子类里只能调用超类的designated初始化器,这是Swift早期版本的一个限制,所以譬如完成CCSprite子类

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读