티스토리 뷰


출처

http://kka7.tistory.com/8





함수 정의와 호출


기본 형식

func greetAgain(person: String) -> String {

    return "Hello again, " + person + "!"

}


print(greetAgain(person: "Anna"))



파라미터 없는 함수

func sayHelloWorld() -> String {

    return "hello, world"

}


print(sayHelloWorld())



여러개의 파라미터를 가진 함수

func greet(person: String, alreadyGreeted: Bool) -> String {

    if alreadyGreeted {

        return greetAgain(person: person)

    } else {

        return greet(person: person) }

}


func greet(person : String) -> String {

    return "Hello, \(person)!"

}


func greetAgain(person : String) -> String {

    return "Hello again, \(person)!"

}


print(greet(person: "Tim", alreadyGreeted: true))




반환값이 없는 함수


func greet(person: String) {

    print("Hello, \(person)!")

}


greet(person: "Dave")




반환값이 여러개인 함수

여러개의 값을 반환하기 위해 함수의 반환 타입을 
하나의 합성된 반환값의 부분으로 튜플 타입을 사용한다.

func minMax(array : [Int]) -> (min : Int, max : Int) {

    var currentMin = array.first!

    var currentMax = array.first!

    

    for value in array {

        if value < currentMin {

            currentMin = value

        } else if value > currentMax {

            currentMax = value

        }

    }

    

    return (currentMin, currentMax)

}




옵셔널 튜플 반환타입

func minMax(array : [Int]) -> (min : Int, max : Int)? {

    if array.isEmpty {

        return nil

    }

    

    var currentMin = array.first!

    var currentMax = array.first!

    

    for value in array {

        if value < currentMin {

            currentMin = value

        } else if value > currentMax {

            currentMax = value

        }

    }

    

    return (currentMin, currentMax)

}


let array = [8, -6, 2, 109, 3, 71]


if let tuple = minMax(array: array1) {

    print ("min : \(tuple.min) / max : \(tuple.max)")

} else {

    print ("array empty")

}




매개변수 이름

각 함수 매개변수는 매개변수 이름을 가진다.

func someFunction(firstParameterName: Int, secondParameterName: Int) {

}


someFunction(firstParameterName: 1, secondParameterName: 2)




인자 레이블

매개변수 이름 앞에 인자 레이블을 작성하며, 
공백으로 구분된다.

func someFunction(argumentLabel parameterName: Int) {

    // In the function body, parameterName refers to the argument value 

    // for that parameter.

}


func greet(person : String, from hometown : String) -> String {

    return "Hello! \(person)! Glad you could visit from \(hometown)"

}


print(greet(person: "Bill", from: "Cupertino"))




인자 레이블 생략하기

( _ ) 를 사용하면 parameter 이름을 생략할 수 있다.

func someFunction(_ firstParameterName : String, secondParameterName : String) {

    

}


someFunction("Bill", secondParameterName: "")





기본 매개변수 값

func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {

 

}


someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6)

someFunction(parameterWithoutDefault: 4)




입출력 파라미터 (In-Out)

함수 매개변수는 기본적으로 상수이다.
함수의 본문에서 함수 매개변수의 값을 변경하려고 시도하면 컴파일 에러가 발생한다.

매개변수의 값 변경을 원하고 함수 호출이 종료된 후에도
변경된 것을 유지하길 원한다면
inout 매개변수로 선언해야한다.

func swapTwoInts(_ a: inout Int, _ b: inout Int) {

    let temporaryA = a

    a = b

    b = temporaryA

}


var first = 3

var second = 107

swapTwoInts(&first, &second)

print("first : \(first) / second : \(second)")



 

함수 타입


언제나 함수는 parameter, return 값에 따른 특정 타입을 가진다.
Swift 에서는 함수 타입에 따라 변수를 정의할 수 있다.

func multiplyTwoInts(_ a: Int, _ b: Int) -> Int {

    return a * b

}


var function : (Int, Int) -> Int

function = multiplyTwoInts(_:_:)

function(2, 3)




매개변수 타입처럼 사용하는 함수 타입


(Int, Int) -> (Int) 와 같은 함수타입을 다른 함수의 매개변수로 사용할수도 있다.

func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {

    print("Result: \(mathFunction(a, b))")

}


printMathResult(multiplyTwoInts, 3, 5)





반환 타입처럼 사용하는 함수 타입


func stepForward(_ input: Int) -> Int {

    return input + 1

}


func stepBackward(_ input: Int) -> Int {

    return input - 1

}


func chooseStepFunction(backward: Bool) -> (Int) -> Int {

    return backward ? stepBackward : stepForward

}




중첩된 함수

중첩된 함수는 기본으로 외부 영역으로부터 숨겨지지만
감싸고 있는 함수에 의해서 호출하고 사용될 수 있다.

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)


while currentValue != 0 {

    print("\(currentValue)... ")

    currentValue = moveNearerToZero(currentValue)

}


print("zero!")










공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함