0

My group and I are writing a space shooter game. We store the player and hazards in and NSMutableArray called objects. I just finished writing a function to control the players movement using tilt controls, but to test it I need to pass in the player when I call the function and I can't seem to access the player from the objects array. Here's my code:

public var objects: NSMutableArray!

objects.add(Player(pos: GLKVector3(v: (0.0, 0.0, -5.0)), up: GLKVector3(v: (0.0, 1.0, 0.0)), forw: GLKVector3(v: (0.0, 0.0, -1.0)), hp: 5, dmg: 1));
        objects.add(Satellite(pos: GLKVector3(v: (2.0, -2.0, -40.0)), up: GLKVector3(v: (0.0, 1.0, 0.0)), forw: GLKVector3(v: (0.0, 0.0, -1.0)), hp: 5, dmg: 1, spd: 2.0));
        objects.add(Satellite(pos: GLKVector3(v: (-2.0, 2.0, -50.0)), up: GLKVector3(v: (0.0, 1.0, 0.0)), forw: GLKVector3(v: (0.0, 0.0, 1.0)), hp: 1, dmg: 1, spd: 2.0));

myDeviceMotion(objects.object(at: 0));
1
  • 3
    If you are programming in swift then do not use NSMutableArray, use the native Array type instead. Commented Feb 14, 2020 at 8:05

1 Answer 1

0

Not use NSMutableArray, user Arrays and pass temp Protocol to your classes.

protocol MyTempProtocol {  }

class Player: MyTempProtocol {
    // ...
}

class Satellite: MyTempProtocol {
    // ...
}

/// --------------
let player1 = Player()
let player2 = Player()
let satellite1 = Satellite()
let satellite2 = Satellite()

var objects = [MyTempProtocol]()
objects.append(player1)
objects.append(satellite1)
objects.append(satellite2)
objects.append(player2)


if let objectIsPlayer = objects[0] is Player {
    // ...
} else if let objectIsSatellite = objects[0] is Satellite {
    // ... 
} else {
    // ...
}
Sign up to request clarification or add additional context in comments.

3 Comments

No need for a custom protocol in this case, use Any instead
Any was not type-safe enough, you can put everything into that array like Bool, String, Structs, UIView and so on. Use custom protocol to handle little access control inside your array.
And you can let anything conform to MyTempProtocol like Bool, String and so on so there is little gain since you will always have to do the check with is anyway. A little more clarity yes but also more to maintain.

Your Answer

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.