1
\$\begingroup\$

I have an SKLabel attached to a parent SKNode and an array of strings:

let configText:[String] = [
 "Configuration",
 "Do stuff",
 "Do more stuff",
 "Nil",
 "It is the void"]

The array is looped through with the following:

parentNode_Label.run(
 SKAction.sequence([
 SKAction.run{
 if self.counter == self.configText.count - 1
 { self.counter = 0 } },
 SKAction.wait(forDuration: 3.0),
 SKAction.run { self.sprite_Label.text = self.configText[self.counter + 1] },
 SKAction.fadeIn(withDuration: 0.5),
 SKAction.wait(forDuration: 3.0),
 SKAction.fadeOut(withDuration: 0.5),
 SKAction.run{ self.counter += 1 }
 ]).forever()
)
extension SKAction
public func forever() -> SKAction { return SKAction.repeatForever( self ) }
}

It works but seems kind of clunky/hacky. Is there a simpler, more efficient yet readable way to do this?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Nov 25, 2017 at 7:25
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$
  • The first array element configText[0] is never used, so you can remove it from the array (and modify the index calculations accordingly).

  • Incrementing the counter with wrap-around can be simplified using the remainder operator:

    self.counter = (self.counter + 1) % self.configText.count
    
  • The three "run" actions can be combined into one.

  • Inside the actions array you can refer to the SKAction members without specifying the type explicitly, e.g. .wait instead of SKAction.wait.

Putting it all together:

parentNode_Label.run(
 SKAction.sequence([
 .wait(forDuration: 3.0),
 .run {
 self.sprite_Label.text = self.configText[self.counter]
 self.counter = (self.counter + 1) % self.configText.count
 },
 .fadeIn(withDuration: 0.5),
 .wait(forDuration: 3.0),
 .fadeOut(withDuration: 0.5),
 ]).forever()
)

Also have a look at the Swift naming conventions:

Names of types and protocols are UpperCamelCase. Everything else is lowerCamelCase.

For example: parentNode, textLabel, without underscores.

answered Nov 25, 2017 at 11:23
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.