Objective-C equivalent for Smalltalk's at: aKey ifAbsentPut: aBlock?

89 Views Asked by At

Consider the following code:

rankedGames at: rank ifAbsentPut: [SortedCollection sortBlock: [:one :two | one name < two name]].

I've only seen this "convenience" method used a couple of times in Smalltalk code, and then there is that SortedCollection there with no direct Obj-C equivalent. What is the Objective-C equivalent?

1

There are 1 best solutions below

1
On

What is the Objective-C equivalent?

There isn't a direct equivalent. NSMutableArray gives you an ordered collection that can be sorted, so that's probably the closest to SortedCollection. I don't know of a single-line equivalent of at:ifAbsentPut:, so you'd normally do that in a few lines:

// assume rankedGames is an array of mutable arrays
NSMutableArray *games = rankedGames[rank];
if (games == nil) {
    games = [NSMutableArray array];
}