一個可行的方法:
讓我們假設你可以拼湊的(實際上有些乏味)使用rangeOfString和rangeOfCharacter調用在一起,可以寫這樣的方法:
-(NSInteger)numberOfMatchesFoundInString:(NSString*)inputString;
這讓你傳入一個字符串,並根據找到的匹配數返回一個0,1,2 ...。
要以高度可讀的方式使用此便捷結果,可以使用switch語句。
NSInteger* matches = [self numberOfMatchesFoundInString:someString];
switch (matches) {
case 0:
//execute some code here for when no matches are found
break;
case 1:
//execute some different code when one match is found
break;
case 2:
//you get the idea
break;
default:
//some code to handle exceptions if the numberOfMatchesFoundInString method went horribly wrong
break;
當然,有些人會告訴你,這是功能上並不比調用
if (someCondition) {
//do some stuff
}
else if (someOtherCondition) {
//do some different stuff
}
etc...
不同,但說真的,你可以讓任何一個工作。
你的意思是,如果一至三個被發現執行相同的塊,或者如果發現執行X,如果兩個執行Y,如果三個執行Z' – Kevin