0

I'm currently trying to look at the first two characters of a string, and depending on what they are, I want to do something. There are 6 possibilities: AA, BB, CC, AB, BC, CA.

I tried the following but kept getting the following error:

enter image description here

NSString *housing = [myArray firstObject];
    switch([housing compare:housing options:@"AA", @"BB", @"CC", @"AB", @"BC", @"CA" range:2]) {

        case 0:
            break;

        case 1:
            break;

        case 2:
            break;

        case 3:
            break;

        case 4:
            break;

        case 5:
            break;

        default:
            break;
    }
3
  • 1
    What's the warning say? Commented Feb 16, 2014 at 7:17
  • But generally, I think you're using the compare method wrong… Going to double check before answering... Commented Feb 16, 2014 at 7:21
  • Updated my answer to include the error. It's asking for an expected ":" at range. I agree, I'm pretty sure this is completely wrong. I guess what I'm asking is what's the best way to go about this. Thanks for your help! Commented Feb 16, 2014 at 7:21

1 Answer 1

4

(1) The NSString immediately before compare and the NSString immediately after compare are the strings you are comparing to one another, so to compare "housing" to "housing" doesn't make sense.

(2) You're misusing options. options only accepts the following search options -- NSCaseInsensitiveSearch, NSLiteralSearch, NSNumericSearch.

(3) And range needs to be an NSRange, not just a number.

Here's the class reference.

Edit: Just thought up a pretty elegant solution, if I don't say so myself… (It's 3 AM here though, so you should double check the logic to make sure I'm not delirious.)

// Check to see if the first 2 characters of the housing string are in an array of the characters
switch([[@"AA", @"BB", @"CC", @"AB", @"BC", @"CA"] indexOfObject:[housing substringWithRange:NSMakeRange(0, 2)]){

    case 0: // Do something if first 2 characters are AA
    break;

    case 1: // Do something if first 2 characters are BB
    break;

    // etc ...

    default: // Do something if not found
    break;
}
Sign up to request clarification or add additional context in comments.

Comments

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.