您当前的位置: 首页 >  swift

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

发布时间:2016-04-10 19:37:08 ,浏览量:0

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

关注
打赏
1688896170
查看更多评论

暂无认证

  • 0浏览

    0关注

    108472博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0853s