LoginSignup
6
6

More than 5 years have passed since last update.

関数の定義方法いろいろ

Last updated at Posted at 2014-12-20

Swift完全初心者のメモです。

-> で戻り値の型を指定

func greet(name: String, day: String) -> String {
    return "Hello \(name), today is \(day)."
}
greet("Bob", "Tuesday")

tupleを使えば複数の戻り値を設定できる

func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
    var min = scores[0]
    var max = scores[0]
    var sum = 0
    for score in scores {
        if score > max {
            max = score
        } else if score < min { 
            min = score
        }
        sum += score
    }
    return (min, max, sum)
}
let statistics = calculateStatistics([5, 3, 100, 3, 9])
statistics.sum
statistics.2

関数はネストできる

func returnFifteen() -> Int {
    var y = 10
    func add() {
        y += 5
    }
    add()
    return y
}
returnFifteen()

関数はファーストクラスなので戻り値で他の関数自体を返せる

func makeIncrementer() -> (Int -> Int) {
    func addOne(number: Int) -> Int {
        return 1 + number
    }
    return addOne
}
var increment = makeIncrementer()
increment(7)

関数は引数に他の関数を取れる

func hasAnyMatches(list: [Int], condition: Int -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}
func lessThanTen(number: Int) -> Bool {
    return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, lessThanTen)

クロージャ(後で呼ぶことが出来るコードのブロック)も使える。

Objective-Cでいうところのブロックのようなもの。

func printMathResult(mathFunction: (Int, Int) -> Int, a: Int, b: Int) {
println("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
// prints "Result: 8"

外部パラメータ

引数の前にスペースを空けて外部パラメータ名を付けられる。
関数を使う人間が、各引数がどういう役割をするのか分かりやすいようにできる。

func join(string s1: String, toString s2: String, withJoiner joiner: String)
-> String {
    return s1 + joiner + s2
}

呼び出し側では、

join(string: "hello", toString: "world", withJoiner: ", ")
// returns "hello, world"

便利。

# を使えばローカル名と外部パラメータ名を兼用して宣言できる。

func containsCharacter(#string: String, #characterToFind: Character) -> Bool {
    for character in string {
        if character == characterToFind {
            return true
        }
    }
    return false
}

let containsAVee = containsCharacter(string: "aardvark", characterToFind: "v")
// containsAVee equals true, because "aardvark" contains a "v"

便利。

引数のデフォルト値

func join(string s1: String, toString s2: String,
    withJoiner joiner: String = " ") -> String {
        return s1 + joiner + s2
}

join(string: "hello", toString: "world", withJoiner: "-")
// returns "hello-world"

join(string: "hello", toString: "world")
// returns "hello world"

外部パラメータ名を与えなくても、ローカル名が外部パラメータ名みたいに使える。

func join(s1: String, s2: String, joiner: String = " ") -> String {
    return s1 + joiner + s2
}

join("hello", "world", joiner: "-")
// returns "hello-world"
6
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
6
6