initialization - Is setting of non-optional ivars demanded in all init methods? -
i'm trying create skspritenode subclass. plan allow handle of setup internally annoyingly seems enforce quite bit of code-duplication, in particular when setting non-optional ivars , constants.
class trollspriteregular : skspritenode{ allow head : skspritenode allow body : skspritenode init(){ head = skspritenode(color: skcolor.orangecolor(), size: cgsizemake(60, 60)) body = skspritenode(color: skcolor.purplecolor(), size: cgsizemake(40, 60)) super.init() } // desginated intiallizer init(texture: sktexture!, color: uicolor!, size: cgsize) { head = skspritenode(color: skcolor.orangecolor(), size: cgsizemake(60, 60)) body = skspritenode(color: skcolor.purplecolor(), size: cgsizemake(40, 60)) super.init(texture: texture, color: color, size: size) } } if seek remove creation of head or body either 1 of 2 initializers results in compiler error , unable build. there way avoid this, or perhaps above patter not particularly swift-friendly?
i "need" init method allow creating new instances using let trollsprite = trollspriteregular().
edit: ok above can simplified defining constants when they're declared.
class trollspriteregular : skspritenode{ allow head = skspritenode(color: skcolor.orangecolor(), size: cgsizemake(60, 60)) allow body = skspritenode(color: skcolor.purplecolor(), size: cgsizemake(40, 60)) ... if add together variable should receive value init-method have same problem. e.g.:
let trollname : string init(name :string){ trollname = name super.init(texture: nil, color: nil, size: cgsizezero) } this forcefulness me define trollname both in own init(name:) , in designated initializer. oh, well.
a designated initializer required initialize of class's state. in convenience initializer, can delegate responsibility designated initializer.
however, in case looks want 2 designated initializers. since these variables don't depend on input initializer value, can define value in declaration. here's less repetitive version of class:
class trollspriteregular : skspritenode { allow head : skspritenode = skspritenode(color: skcolor.orangecolor(), size: cgsizemake(60, 60)) allow body : skspritenode = skspritenode(color: skcolor.purplecolor(), size: cgsizemake(40, 60)) } initialization sprite-kit swift subclassing
No comments:
Post a Comment