개발 일기

Function ? 본문

컴퓨터 언어/swift

Function ?

이건욱

Swift에서는 함수를 다음과 같이 다양한 방법으로 작성이 가능합니다.

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

// person 이라는 매개변수를 받아서 String으로 Return 합니다.

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

// _ 하는 이유는 나중에 이 함수를 호출을 했을때 이름을 지정을 안하기 위해서 작성을 했습니다.
// 위와 같이 person을 받고 String을 Return 합니다.

func sayHelloWorld() -> String {
    return "hello, world"
}

// 아무 값을 안받고 String을 Return 합니다.

func greet2(person: String) {
    print("Hello, \(person)!")
}
// person이라는 매개변수를 받고 Return은 없습니다.

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)
}
'// [Int] 라는 타입에 array를 받고 tuple type을 통해서 하나이상의 값을 Return 할수가 있습니다.


func optionalMinMax(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)
}
// tuple type을 optional 해서 Return을 합니다.

 

 

그래서 호출하는 다양한 방법으로 호출이 가능합니다.

print(greet(person: "Anna"))
// Prints "Hello, Anna!"

print(greet1("Test"))
// Prints "Test"

print(sayHelloWorld())
// Prints "hello, world"

greet2(person: "Dave")
// No Return Value

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"

if let bounds = optionalMinMax(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"

Swift는 함수는 single expression이기 때문에 아래에 같은 함수는 동일한 행동을 합니다.

func greeting(for person: String) -> String {
    "Hello, " + person + "!"
}
print(greeting(for: "Dave"))
// Prints "Hello, Dave!"

func anotherGreeting(for person: String) -> String {
    return "Hello, " + person + "!"
}
print(anotherGreeting(for: "Dave"))
// Prints "Hello, Dave!"

 

Swift는 다른 언어와는 다르게 Argument Label 이랑 Parametar Name이 존재합니다.

func someFunction(argumentLabel parameterName: Int) {
    // In the function body, parameterName refers to the argument value
    // for that parameter.
}

argumentLable은 호출을 할때 사용을 하고 parameterName은 함수안에서 사용을 합니다.

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) {
    // In the function body, firstParameterName and secondParameterName
    // refer to the argument values for the first and second parameters.
}
someFunction(1, secondParameterName: 2)

 

함수에 대해서 기본값을 작성하고 싶은 경우에는 다음과 같이 할수가 있습니다.

func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {
    // If you omit the second argument when calling this function, then
    // the value of parameterWithDefault is 12 inside the function body.
}
someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6) // parameterWithDefault is 6
someFunction(parameterWithoutDefault: 4) // parameterWithDefault is 12

 

함수에 호출을 할때 매개변수를 zero or N개 이상에 값을 받고 싶은 경우에는 다음과 같이 할수있습니다.

func arithmeticMean(_ numbers: Double...) -> Double {
    var total: Double = 0
    for number in numbers {
        total += number
    }
    return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
// returns 3.0, which is the arithmetic mean of these five numbers
arithmeticMean(3, 8.25, 18.75)
// returns 10.0, which is the arithmetic mean of these three numbers

 

기본적으로 함수를 호출을 했을 때 함수 안에서 매개변수에 값을 변경을 했을 때 이 함수를 호출한 밖에 있는 변수는 영향을 받지가 않습니다.

하지만 받고 싶은 경우에는 다음과 같이 '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"

 

마지막으로 이때 까지 저희가 한것은 global scope에서 진행을 했습니다.

 

하지만 함수안에서 함수를 만들수도 있습니다.

이런 함수같은 경우에는 기본적으로는 밖에서 호출을 할수가 없지만 다음과 같은 방법으로도 여전히 가능합니다.

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 now refers to the nested stepForward() function
while currentValue != 0 {
    print("\(currentValue)... ")
    currentValue = moveNearerToZero(currentValue)
}
print("zero!")
// -4...
// -3...
// -2...
// -1...
// zero!

'컴퓨터 언어 > swift' 카테고리의 다른 글

Enumerations  (0) 2020.06.03
Closures ?  (0) 2020.05.17
Control Flow ?  (0) 2020.05.10
Collection Type ?  (0) 2020.05.03
Strings and Characters  (0) 2020.05.01
Comments