2011-12-22 4 views
10

可能性の重複:
Declaring variables inside a switch statementObjective-Cのswitch文

私は私はObjective-Cの中の特定のswitch文を書いてみましょうするためにはXCodeを得る難しさを抱えています。私は文法に慣れていて、if/elseブロックとして書き直すことができますが、私は興味があります。

switch (textField.tag) { 
     case kComment: 
      ingredient.comment = textField.text; 
      break; 
     case kQuantity: 
      NSLog(@""); // removing this line causes a compiler error   
      NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init]; 
      fmt.generatesDecimalNumbers = true; 
      NSNumber *quantity = [fmt numberFromString:textField.text]; 
      [fmt release]; 
      ingredient.quantity = quantity; 
      break; 
    } 

私は構文エラーが表示されませんが、これを許可するにはコンパイラを騙す必要があります。

答えて

15

ラベルの後に変数宣言を追加することはできません。たとえば、NSLog()を呼び出す代わりにセミコロンを追加できます。または、スイッチの前に変数を宣言します。または、別の{}を追加します。

+0

...これを試してみてください。 – Ariel

+0

はい、キーストロークの回数は最小ですが、文脈によっては最も美しい解決策が異なるかもしれません:) –

+0

これが私があなたの答えを投票した理由です: – Ariel

-2

switchステートメント内の変数宣言部を削除します。

switch文内でObjective-Cに変数を作成することはできません。

NSNumberFormatter *fmt = nil; 
NSNumber *quantity = nil; 
switch (textField.tag) { 
     case kComment: 
      ingredient.comment = textField.text; 
      break; 
     case kQuantity: 
      fmt = [[NSNumberFormatter alloc] init]; 
      fmt.generatesDecimalNumbers = true; 
      quantity = [fmt numberFromString:textField.text]; 
      [fmt release]; 
      ingredient.quantity = quantity; 
      break; 
    } 

最も簡単な方法は、ケースと宣言間の後にセミコロンを置くことです

+1

それはあなたができるように見えます - そして、なぜそうは見えないのですか? switch文の2行目で宣言が機能します。たとえ最初の行がちょうど ';' – Jhong