LoginSignup
128
119

More than 5 years have passed since last update.

Swiftのメソッド記法をまとめてみた

Posted at

引数・返り値のあるメソッド

func method(intValue: Int) -> Bool {
    return true
}
method(1)

引数・返り値がないメソッド

func method() {
}
method()

引数が複数あるメソッド

func method(intValue1: Int, intValue2: Int) {
}
method(1, intValue2: 2) // 2つ目以降の引数にはラベルが必要になる

引数のラベルを省略する

_を使うとintValue2を省略できます。

func method(intValue1: Int, _ intValue2: Int) {
}
method(1, 2)

第一引数もラベル必須にする

// Swift1.2までは method(#intValue1: Int, intValue2: Int)みたいな書き方もできた
func method(intValue1 intValue1: Int, intValue2: Int) {
}
method(intValue1: 1, intValue2: 2)

デフォルト引数

全ての引数を省略

func method(intValue1: Int = 0, intValue2: Int = 1) {
}
method()

第一引数だけ省略

func method(intValue1: Int = 0, intValue2: Int = 1) {
}
method(intValue2: 2)

真ん中の引数だけ省略

func method(intValue1: Int = 0, intValue2: Int = 1, intValue3: Int = 2) {
}
method(1, intValue3: 2)

可変長引数

func method(intValue1: Int, intValue2: Int...) {
    print(intValue2) // [2, 3, 4, 5]、配列になっている
}
method(1, intValue2: 2, 3, 4, 5)

可変長引数はデフォルト値を持てません。

// 下2つはエラー
func method(intValue1: Int, intValue2: Int... = [1, 2, 3]) {}
func method(intValue1: Int, intValue2: Int... = 1) {}

エラーをthrowし得るメソッド

enum MyError: ErrorType { case A, B, C }

func method(intValue1: Int, intValue2: Int) throws {
    throw MyError.A
}
try? method(1, intValue2: 2)

参照渡し

var intValue = 1
func method(intValue1: Int, inout intValue2: Int) {
    intValue2 = 2
}
method(1, intValue2: &intValue)
print(intValue) // → 2

カリー化

残念ながらSwift3からはなくなってしまうみたいです。

func method(intValue1: Int)(intValue2: Int) {
}
method(1)(intValue2: 2)

引数の遅延実行(@autoclosure)

func method(intValue1: Int, @autoclosure intValue2: () -> Int) {
    intValue2()
}
method(1, intValue2: 2)

autoclosureはこちらで詳しく書いてみました。
autoclosureというマニアックで少し面白い機能

Genericsを使ったメソッド

Genericsを使えばメソッドに好きな型の値を入れる事ができます。

func method<T>(value: T) {
    print(value)
}
method([1, 2, 3])
method("String")

Protocolを使って制限をかける事ができます。

func method<T: CollectionType>(value: T) {
    print(value)
}
method([1, 2, 3]) 
method("String") // → エラー

whereを使っても同じ結果になります。

func method<T where T: CollectionType>(value: T) {
    print(value)
}
method([1, 2, 3])

引数にブロックを渡す

func method(intValue1: Int, block1: () -> Int) {
}
method(1, block1: { return 1 })

最後の引数がブロックの場合はブロックを()の外に出せます。

func method(intValue1: Int, block1: () -> Int) {
}
method(1) { return 1 }

引数がブロック1つの場合は()も省略できます。

func method(block: () -> Int) {
}
method { return 1 }

エラーを投げ得るブロックを引数にする

enum MyError: ErrorType { case A, B, C }

func method(block: () throws -> Int) {
}
method {
    throw MyError.A
    return 1
}
128
119
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
128
119