티스토리 뷰

1. Defining and Calling

swift에서는 아래와 같이 함수를 선언할 수 있다.

func greet(person: String) -> String {
 let greeting = "Hello, " + person + "!"
 return greeting
}

func 키워드를 앞에 붙이고 선언하며, person 이라는 String 파라미터를 인자로 받고 String 을 반환 값으로 반환하는 함수이다.


2. 복수의 값을 반환하는 함수

아래와 같이 튜플을 함수의 반환 값으로 사용하여 복수의 값을 반환할 수도 있다.

func minMax(array: [Int]) -> (min: Int, max: Int) {
    var currentMin = array[0]
    var currentMax = array[0]
        
    for value in array[1..<array.count] {
        if value < currentMin {
            currentMin = value
        } else if value > currentMax {
            currentMax = value
        }
    }
    return (currentMin, currentMax)
}

let bounds = minMax(array: [8, -6, 2, 109, 3, 71])

print("min is \(bounds.min) and max is \(bounds.max)")

3. 옵셔널 튜플 반환형

위 예제와는 달리 반환 값을 옵셔널로 선언하게 되면, 해당 반환 값은 옵셔널이 되어 반드시 if let 과 같은 옵셔널 체인을 사용하거나 ! 를 사용하여 강제 unwrapping 해야 한다.

func minMax(array: [Int]) -> (min: Int, max: Int)? {
    if array.isEmpty { return nil }
    var currentMin = array[0]
    var currentMax = array[0]
    for value in array[1..<array.count] {
        if value < currentMin {
            currentMin = value
        } else if value > currentMax {
            currentMax = value
        }
    }
    return (currentMin, currentMax)
}
if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) {
    print("min is \(bounds.min) and max is \(bounds.max)")
}
// Prints "min is -6 and max is 109"

3. 파라미터

위 예제들의 경우처럼 함수 호출 시 적절한 파라미터 이름을 지정하여 함수 내부와 함수 호출 시 사용할 수 있다.

func someFunction(firstParameterName: Int, secondParameterName: Int) {
    // 함수 내부에서 firstParameterName와 secondParameterName의 인자를 사용합니다.
}
someFunction(firstParameterName: 1, secondParameterName: 2)

 

또한 파라미터 앞에 인자 라벨을 지저하여 실제 함수 내부에서 해당 인자를 식별하기 위한 이름과 함수 호출 시 사용할 이름을 다르게 하여 사용할 수도 있다.

func someFunction(argumentLabel parameterName: Int) {
    // 함수 안애서 parameterName로 argumentLabel의 인자값을 참조할 수 있습니다.
}
func greet(person: String, from hometown: String) -> String {
    return "Hello \(person)!  Glad you could visit from \(hometown)."
}
print(greet(person: "Bill", from: "Cupertino"))
// Prints "Hello Bill!  Glad you could visit from Cupertino."

 

파라미터 앞에 _ 를 붙여 함수 호출 시 인자 값을 생략할 수 있다.

func someFunction(_ firstParameterName: Int, secondParameterName: Int) {
    // 함수 안에서 firstParameterName, secondParameterName
    // 인자로 입력받은 첫번째, 두번째 값을 참조합니다.
}
someFunction(1, secondParameterName: 2)

 

아래와 같이 함수의 파라미터의 기본 값을 = 을 활용하여 지정할 수 있다.

func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {
    // 함수 호출시 두번째 인자를 생략하면 함수안에서
    // parameterWithDefault값은 12가 기본 값으로 사용됩니다.
}
someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6) // parameterWithDefault는 6
someFunction(parameterWithoutDefault: 4) // parameterWithDefault는 12

4. 인 - 아웃 파라미터

 Swift는 C++ 의 ref 와 동일하게 인자로 들어오는 변수를 직접 수정할 수 있는 inout 키워드를 제공한다.

 

func swapTwoInts(_ a: inout Int, _ b: inout Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

var someInt = 3
var anotherInt = 107

swapTwoInts(&someInt, &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
// Prints "someInt is now 107, and anotherInt is now 3"

5. 중첩 함수

함수를 다른 함수의 body에서 동작하도록 선언할 수도 있다. 

func chooseStepFunction(backward: Bool) -> (Int) -> Int {
    func stepForward(input: Int) -> Int { return input + 1 }
    func stepBackward(input: Int) -> Int { return input - 1 }
    return backward ? stepBackward : stepForward
}
var currentValue = -4
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
// moveNearerToZero는 이제 중첩 돼 있는 stepForward() 함수를 가르킵니다.
while currentValue != 0 {
    print("\(currentValue)... ")
    currentValue = moveNearerToZero(currentValue)
}
print("zero!")
// -4...
// -3...
// -2...
// -1...
// zero!

 

 

Comments