2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swiftで可変長引数に渡す引数が0個のときのやり方と挙動まとめ

Last updated at Posted at 2017-03-30

可変長引数に渡す引数が0個のときのをやり方と挙動をSwift 3.0.2で検証。

外部引数名がないもの

単に引数を省くだけである。

func testValArg(_ a: Int...) {
}
testValArg() //省くだけ

外部引数名があるもの

これも外部引数名ごと省くだけである。外部引数名をつけてはだめ。

func testValArg(a: Int...) {
}
testValArg() //まるごと省くだけ

可変長引数以外が同名の関数が他に定義されているとき

外部引数ごと省くとなると同名関数とバッティングする。例えばこの場合どうなるか。

func testValArg() {
	print("なし")
}
		
func testValArg(a: Int...) {
	print("あり")
}

testValArg() //なしと表示

これはコンパイルエラーにはならない。
呼ばれるのは引数なしの方になる。
この同名関数を削除すると当然可変長引数のものが呼ばれる。

func testValArg(a: Int...) {
	print("あり")
}

testValArg() //ありと表示

ちなみに

外部引数名をつけたときはエラーになるが、そのエラーメッセージは定義されている引数の個数によって異なる。
1つのとき

func testValArg(a: Int...) {
}
testValArg(a:) //Expression resolves to an unused function

2つのとき

func testValArg(a: Int, b: Int...) {
}

testValArg(a: 1, b:) //Expected expression in list of expressions

引数が2つのときは引数が与えられていない状態と解釈出来ているが、1つのときは(実行指令ではなく)単に関数が書かれている状態という解釈と思われる。例えば

let atodeyaru: (Int...) -> Void = testValArg(a: )

のような使い方をするときの解釈である。

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?