LoginSignup
5
5

More than 5 years have passed since last update.

Swiftのローカルスコープで変数束縛したい場合

Last updated at Posted at 2014-08-30

Objective-Cの場合は以下のようにシンプルに書けますが…

-(void) doSomething {
  NSMutableArray *items = [[NSMutableArray alloc] init];
  {
    NSString *str = @"a";
    [items addObject:str];
  }
  {
    NSString *str = @"b";
    [items addObject:str];
  }
  {
    NSString *str = @"c";
    [items addObject:str];
  }
}

Swiftでやる場合少し捻る必要があります。
4パターン考えてみました。

if文のスコープを使う方法

func doSomething() {
  let items = NSMutableArray()

  if true {
    let str = "a"
    items.addObject(str)
  }

  if true {
    let str = "b"
    items.addObject(str)
  }

  if true {
    let str = "c"
    items.addObject(str)
  }
}

switch文のパターンマッチを使う方法

func doSomething() {
  let items = NSMutableArray()

  switch ("a") {
  case let str:
    items.addObject(str)
  }

  switch ("b") {
  case let str:
    items.addObject(str)
  }

  switch ("c") {
  case let str:
    items.addObject(str)
  }
}

無名関数の引数束縛を使う方法

func doSomething() {
  let items = NSMutableArray()

  { (str) -> Void in
    items.addObject(str)
  }("a")

  { (str) -> Void in
    items.addObject(str)
  }("b")

  { (str) -> Void in
    items.addObject(str)
  }("c")
}

無名関数のスコープを使う方法

func doSomething() {
  let items = NSMutableArray()

  { () -> Void in
    let str = "a"
    items.addObject(str)
  }()

  { () -> Void in
    let str = "b"
    items.addObject(str)
  }()

  { () -> Void in
    let str = "c"
    items.addObject(str)
  }()
}

うーん、どれもいまいち綺麗に書けない。

5
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5