jdnoon
jdnoon

Reputation: 1879

Objective-C Array Index Wrap

I'm wondering if it is possible to wrap a Array in Objective-C

Example:

I have an Array called characters that contains the alphabet:

abcdefghijklmnopqrstuvwxyz

Being the alphabet, it only contains 26 characters.

I would like to be able to get the objectAtIndex of say 30, however it returns beyond bounds (understandable).

NSString *letter = [characters objectAtIndex:30];

What I would like is the Array to wrap around. Example, the objectAtIndex of 30 to return d, the 4th Character as it wraps from last character to the first.

Here is the specific line from my code:

NSString *encoded = [characters objectAtIndex:[characters indexOfObject:chars] + keyNumber % [characters count]];

The variables change depending on other instances, so the objectAtIndex will vary.

Thank you your time is much appreciated. Any queries please ask.

James Noon.

Upvotes: 0

Views: 105

Answers (3)

Tamás Zahola
Tamás Zahola

Reputation: 9311

You only need a pair of parentheses:

[characters objectAtIndex:([characters indexOfObject:chars] + keyNumber) % characters.count];

Upvotes: 2

Fennelouski
Fennelouski

Reputation: 2431

You could create a category for NSArray and add your own method for objectAtIndex: that takes the index and finds the modulo of the length of the array and then returns the object at that index. Adding a log whenever the given index is greater than the array length would be helpful as well or when the array has a length of 0.

But, I would recommend creating a separate method in that category just for finding the wrapped index and calling it something like objectAtWrappedIndex:.

Upvotes: 1

trojanfoe
trojanfoe

Reputation: 122411

Wrapping is often done using the modulo operator:

NSString *letter = characters[index % 26];
//                                  ^

However better might be:

NSString *characters = @"abcdefghijklmnopqrstuvwxyz";
unichar letter = [characters characterAtIndex:index % 26];

Upvotes: 1

Related Questions