1

Hi, guys!

I'am writing game with SpriteKit framework and I try to make object with several configurations so I have to use static to avoid init method and some boilerplate code with decoder. So I wrote code but I'am not really know if this code is acceptable for creation purpose or not but this code actually works fine.

class Island: SKSpriteNode {

    static func populateIsland(at point: CGPoint) -> SKSpriteNode {
        let islandImageName = configureIslandName()
        let island = SKSpriteNode(imageNamed: islandImageName)
        island.setScale(randomScaleFactor)
        island.position = point

        return island
    }

    fileprivate static func configureIslandName() -> String {
        let distribution = GKRandomDistribution(lowestValue: 1, highestValue: 4)
        let randomNumber = distribution.nextInt()
        let imageName = "pic" + "\(randomNumber)"
        return imageName
    }

    fileprivate static var randomScaleFactor: CGFloat {
        let distribution = GKRandomDistribution(lowestValue: 7, highestValue: 10)
        let randomNumber: CGFloat = CGFloat(distribution.nextInt()) / 10

        return randomNumber
    }
}

So actual example is:

let island = Island.populateIsland(at: CGPoint(x: 100, y: 100))

Thank you for your suggestions in advance!

wm.p1us
  • 2,019
  • 2
  • 27
  • 38

1 Answers1

1

I think this is totally fine.

Static members are used when they are not related to instances of a type, but to the type itself. Since your methods just create and return an SKSpriteNode, it does not need any state and thus, can be independent from instances of the Island type.

I also think that you should rename some of your member names to fit the Swift 3 API guidelines and also to make their purpose clearer. e.g. populateIslands(atPosition:) does not really "populate" islands. It just creates one single island sprite and returns it. I suggest you to rename it to createIsland(at:).

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Yes, thank you. You're right, I've just made quick change to post it here so a little miss from me. Now i'am thinking how to attach instance methods to instance itself because it is just SKSpriteNode :) – wm.p1us Apr 19 '17 at 06:51
  • @wm.p1us What do you mean "attack instance methods to instance itself"? Do you mean "attach"? Instance methods attach to instances by itself, you don't need to do anything. – Sweeper Apr 19 '17 at 06:53