목차

4. Functions and Closure

func

**func funcName(_ paraName: paraType) -> returnType {**

code

}

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

자연스럽게, 함수들은 그들의 매개변수parameter 이름을 그들의 arguments의 라벨로 사용한다.

custom argument label을 매개변수parameter 이름 **앞에** 적고, argument 라벨을 사용하지 않을 경우엔 _ 을 적는다.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/1c2ebc0f-aad3-4f30-9098-8d52c350ce21/Untitled.png

func greet(_ person: String, on day: String) -> String {
    return "Hello \\(person), today is \\(day)."
}
greet("John", on: "Wednesday")
: a custom argument label

tuple

**tuple**을 이용해서 compound value를 만들 수 있다. ex) 함수로부터 여러 값을 반환

tuple의 요소들은 이름 혹은 숫자로부터 참조될 수 있다.

*tuple : 순서가 없는 값의 세트an ordered set of value

func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
    var min = scores[0]  //  score 배열의 첫 번째 원소로 초기화
    var max = scores[0]  //  score 배열의 첫 번째 원소로 초기화
    var sum = 0

    for score in scores {  //  scores 배열 안에 있는 요소 score만큼 반복
        if score > max {
            max = score
        } else if score < min {
            min = score
        }
        sum += score
    }

    return (min, max, sum)
}
let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9])
//max = 100, min = 3, sum =120 => statistics = (100, 3, 120)
print(statistics.sum)
// Prints "120"
print(statistics.2) // statistics의 인덱스 (0, 1, 2)
// Prints "120"

Nested functions