LoginSignup
81
81

More than 5 years have passed since last update.

Swiftにおける名前付き引数

Posted at

今話題の「Swift」をさわってみた。いろいろ感想はあるけど、ざっと見た感じ、「普通のFunction」、「クラスの中でのinit」、そして「その他のメソッド」の3つで、引数に対するスタンスが違うっぽいのが気になった。

Function

普通の関数は、funcキーワードの後に定義をごりごり書く。デフォルトでは、引数に名前はつかない。

func addBy(amount: Int, times: Int) -> Int {
    return amount * times
}
addBy(2, 3) // 6

引数名の前にラベルを置く事で、名前付き引数を実現出来る。

func addBy(amount amount: Int, times times: Int) -> Int {
    return amount * times
}
addBy(amount: 2, times: 3) // 第一引数をamount, 第二引数をtimesという名前で呼び出し

ラベルと引数名が同じなら、#を使う事でさっくり書ける。

func addBy(#amount: Int, #times: Int) -> Int {
    return amount * times
}
addBy(amount: 2, times: 3) // 6

クラスのinit

クラスのinitは、オブジェクト生成時に呼ばれる。何もしなくても基本的に名前付き引数の形で呼び出す事になる。

class Counter {
    var count: Int
    init(count: Int) {
        self.count = count
    }
}
var counter = Counter(0) // Error!
var counter = Counter(count: 0)

関数の定義の時と同様、引数名の前にラベルを置けるみたいだけど、何のメリットがあるかは分からない。

class Counter {
    var count: Int
    init(myCount count: Int) {
        self.count = count
    }
}
var counter = Counter(myCount: 0) // myCountという名前で呼び出し

メソッド

クラスにおけるメソッドの定義では、デフォルトでは第二引数以降を名前付き引数の形で呼び出す事になる。この辺はObjective-Cを踏襲している?

class Counter {
    var count: Int
    init(count: Int) {
        self.count = count
    }
    func incrementBy(amount: Int, times: Int) {
        count += amount * times
    }
}
var counter = Counter(count: 0)
counter.incrementBy(2, times: 3) // {count 6}

これも関数の定義の時と同様、第一引数にもラベルを置いたり、#で名前付き引数にしたり出来る。

class Counter {
    var count: Int
    init(count: Int) {
        self.count = count
    }
    func incrementBy(#amount: Int, times: Int) {
        count += amount * times
    }
}
var counter = Counter(count: 0)
counter.incrementBy(amount: 2, times: 3) // 第一引数も名前付きで呼び出し

所感

普通の関数の定義がベースにあって、initメソッド定義では所定の引数に#がついた扱いになるようなイメージだと思う。名前付き引数が簡単に実現出来るのは、地味かもしれないけど自分としては嬉しい機能。

81
81
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
81
81