Critique my code! I'm new-ish to Swift (:

Yes, let's concentrate on the sorting of items. The way it is now, the Inventory object must know all the types of all the possible items; consider what happens if you add a couple more item subclasses. Just to do the sorting, there will have to be a couple more cases in the if-else, there will be a couple more [Item] arrays in the tuple, and there will be a couple more sorted-by near the end of sortItems. That's rather onerous to have to remember to do all that every time an item is added, and that is only looking at the sorting of the items, I haven't looked at any other implications of adding a new item.

There are many, many possible ways to change it and accomplish the goals of centralising logic inside Item as well as minimising code changes when design (I mean logic/functional design, not how-stuff-looks design!) changes occur. For example, a very straightforward change would be to give each class of item a rank (rank could be an Int var implemented by each Item). Based on your current sort method, the ranks could be, for example: QuestItem = 100, ConsumableItem = 80, GemstoneItem = 60, EquippableItem = 40. Then you get rid of all the tupling and multiple arrays and the appending by having the comparison method compare the ranks first and only when the ranks are equal compare the names. So, all items can be sorted with one call to sort. And adding a new item only requires giving it an appropriate rank and everything else 'just works'.

wrt organising items etc, I'm going to punt on that slightly because I gather that is an important part of game design, and I've never made a game (noughts and crosses doesn't really count, i think). However, I can recommend that you take a look at GameplayKit, specifically the Entity/Component aspects. I think this is a pattern commonly used in games, which is why Apple included it in the GameplayKit. You might get some ideas from this to make an implementation of your own, or you might even decide it fits your needs so well that you could use it directly.

/r/swift Thread Parent