LoginSignup
11
6

More than 5 years have passed since last update.

Swiftの関数の引数(let)を同名変数(var)に置き換える

Last updated at Posted at 2017-02-28

Swiftの関数の引数は値を変更することができません。(Cannot assign to value: 'a' is a 'let')

func method(a: Int) {
  // コンパイルエラー
  a = 1
}

前はこう書けたけど今はこれもコンパイルエラー。(Parameters may not have the 'var' specifier)

func method(var a: Int) {
  a = 1
}

それで、このようにして対処している人もいるのではないでしょうか?

func method(a: Int) {
  var a2 = a
  a2 = 1
}

でも実は変数名変えなくてもいいんですよね。こんな風に書けてしまう。

func method(a: Int) {
  var a = a
  a = 1
}

変数名変えるの嫌ならこれでいいですね。

また、こういうケースでも同名変数を使えたりします。

var a: Any? // aはOptional型
〜〜〜
if let a = a as? Int {
  if a == 1 { // 新しいaはOpational型じゃないからa!にしなくていい
  }
}

意外に知られてなさそうな気がしたので書いておきました。

11
6
0

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
11
6