function

김태현·2022년 2월 18일
0

swift

목록 보기
5/7
post-thumbnail

Functions - The Swift Programming Language (Swift 5.6)

Functions are self-contained chunks of code that perform a specific task.

⇒ 함수란 특정 임수 수행하는 코드의 덩어리


use a tuple type as the return type for a function to return multiple values as part of one compound return value.

⇒ 여러 값을 반환하기


accessed with dot syntax to retrieve the minimum and maximum found values

⇒ dot syntax로 튜플로 반환값 값에 접근 가능


func minMax(array: [Int]) -> (min: Int, max: Int)
.
.
.
let bounds = minMax(array: [8, -6, 2, 109, 3, 71])
print("min is \(bounds.min) and max is \(bounds.max)")

매개변수에 기본값 할당

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

Place parameters that don’t have default values at the beginning of a function’s parameter list, before the parameters that have default values. Parameters that don’t have default values are usually more important to the function’s meaning—writing them first makes it easier to recognize that the same function is being called, regardless of whether any default parameters are omitted.

⇒ 디폴트 값이 존재하는 매개변수는 뒤에 위치해라

⇒ 이유 : 기본값 없는 매개변수가 보통 더 중요하고, 알아보기 쉽고, 디폴트 매개변수 생략하기 편함


variadic parameter accepts zero or more values of a specified type.
The values passed to a variadic parameter are made available within the function’s body as an array of the appropriate type.

variadic parameter 을 통해서 0개 이상의 값을 매개변수로 표현 가능

⇒ 함수 내부에서는 배열로 사용

func arithmeticMean(_ numbers: Double...) -> Double {
    var total: Double = 0
    for number in numbers {
        total += number
    }
    return total / Double(numbers.count)
}

Function parameters are constants by default.
If you want a function to modify a parameter’s value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter
instead.

⇒ 매개변수는 상수라서 변경 불가

in-out parameter를 통해서 매개변수 값 변경 가능


In-out parameters can’t have default values, and variadic parameters can’t be marked as inout.

⇒ in-out parameter는 기본값 가질 수 없고 variadic 매개변수에서 사용 불가

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"

in-out parameters aren’t the same as returning a value from a function.
In-out parameters are an alternative way for a function to have an effect outside of the scope of its function body.

⇒ return 이 보통 외부에 영향을 미치는 유일한 값

⇒ 하지만 in-out parameter은 리턴값과 별개로 외부에 영향을 미침(이유: 매개변수로 전달한 값이 변경됨)


function type

var mathFunction: (Int, Int) -> Int = addTwoInts
print("Result: \(mathFunction(2, 3))")
// Prints "Result: 5"
profile
iOS 공부 중

0개의 댓글