Home Should I be using Classes or Structs for elements stored in a Swift Array
Reply: 0

Should I be using Classes or Structs for elements stored in a Swift Array

user8137
1#
user8137 Published in September 21, 2018, 8:44 am

I would like to mutate a property in a Swift struct, stored within an array. I have done a reassignment dance, but that it doesn't feel right.

I'm encouraged to use Struct's where possible, however this relatively simple use case (below) is pushing me towards using Classes (Reference Types).

Should I be using Classes for Game and/or Player?

Please find below a code sample .. with accompanying UnitTest

Test Summary
• Create a Game
• Create two Players
• Add both Players to Game
• Send message to Game to decrementPlayer
• Game iterates over collection (players)
• Finds player and sends message decrementScore
Test Failed - Players' scores were not as expected (60 & 70 respectively)

struct Game {
    fileprivate(set) var players = [Player]()
}

extension Game {
    mutating func addPlayer(_ player: Player) {
        players.append(player)
    }

    mutating func decrementPlayer(_ decrementPlayer: Player, byScore: Int) {
        for var player in players {
            if player == decrementPlayer {
                player.decrementScore(by: byScore)
            }
        }
    }
}


struct Player {
    var name: String
    var score: Int

    init(name: String, score: Int) {
        self.name = name
        self.score = score
    }

    mutating func decrementScore(by byScore: Int) {
        self.score -= byScore
    }
}

extension Player: Equatable {
    public static func ==(lhs: Player, rhs: Player) -> Bool {
        return lhs.name == rhs.name
    }
}

class GameTests: XCTestCase {

var sut: Game!

func testDecrementingPlayerScores_isReflectedCorrectlyInGamePlayers() {
        sut = Game()
        let player1 = Player(name: "Ross", score: 100)
        let player2 = Player(name: "Mary", score: 100)

        sut.addPlayer(player1)
        sut.addPlayer(player2)
        XCTAssertEqual(2, sut.players.count)    // Passes

        sut.decrementPlayer(player1, byScore: 40)
        sut.decrementPlayer(player2, byScore: 30)
        XCTAssertEqual(60, sut.players[0].score) // Fails - score is 100 .. expecting 60
        XCTAssertEqual(70, sut.players[1].score) // Fails - score is 100 .. expecting 70
    }
}
share|improve this question
  • Please add you test code too. – picciano Feb 12 at 15:55
  • Will do .. thank you @picciano Separated the XCTestCase from existing code sample – MDMonty Feb 12 at 16:29

3 Answers 3

active oldest votes
up vote 3 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.589689 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO