k0b0's record.

Computer Engineering, Arts and Books

Swift入門 関数

関数(メソッド)

 関数の定義する際には関数名、引数、引数の型、処理内容等を記述する。場合によってはラベルを記述してプログラムの可読性を高めることもできる。

関数定義の書式

func 関数名 (<ラベル> 引数1:引数1の型, <ラベル> 引数2 : 引数2の型 ) -> 返り値の型 {
    // 実行する処理
    return 値
}

関数呼び出しの書式

関数名(引数の型:値, 引数の型:値) //通常(引数の型と値)の呼び出し
関数名(引数のラベル:値, 引数ラベル:値) //ラベルを用いた呼び出し

関数の記述例

// Define function.
func sample(name:String, age:Int) -> String {
    return ("My name is " + name + ". " + "I'm " + String(age) + " years old.")
}
var prof = sample(name:"Swift", age:4) //Call sample function.
print(prof)

ラベルを使った関数の記述例

 上記の関数sampleのラベルを使った記述例。

// Define function.
// 引数nameにラベルNAMEをつける
// 引数ageにラベルAGEをつける
func sample(NAME name:String, AGE age:Int) -> String {
    return ("My name is " + name + ". " + "I'm " + String(age) + " years old.")
}
// ラベルNAME、AGEを使って引数の値を設定
var prof = sample(NAME:"Swift", AGE:4) //Call sample function.
print(prof)

実行結果

My name is Swift. I'm 4 years old.

タプルを返り値に使う関数

 関数から複数の値を返したい場合、返り値としてタプルを使うことができる。以下の記述例では関数get_profは引数idを受け取り、idに応じてクラスと所属を設定してタプルとして呼び出し元に返している。

タプルを帰り値に使う関数の記述例

// idを引数として受け取り、タプル(class, affiliation)を返す。
func get_prof(ID id:Int) -> (class:String, affiliation:String) {
    var prof = (class:" ", affiliation:" ")
    switch id {
    case 0...10:
        prof = (class:"computer science", affiliation:"Alpha LAB")
    case 11...20:
        prof = (class:"computer engineering", affiliation:"Bata LAB")
    case 21...30:
        prof = (class:"computer arts", affiliation:"Gamma LAB")
    default:
        prof = (class:"NONE", affiliation:"NONE")
    }
    return prof
}
// 関数呼び出し。IDを関数に渡す。
var prof = get_prof(ID:12)
print(prof.class)
print(prof.affiliation)

実行結果

 上記のプログラムではget_prof(ID:12)としてプログラムを実行している。よって、返り値としてclassはcomputer engineering、affiliationはBata LABとなる。

computer engineering
Bata LAB