티스토리 뷰

Swift

[Swift] inout 매개 변수, 앰퍼샌드(&)

Kim_Baechu 2021. 5. 17. 23:48

In-Out Parameters

copy-in copy-out

 

함수 매개 변수는 기본적으로 상수(Constant)입니다.

함수 매개 변수의 값을 해당 함수의 본문 내에서 변경하려고 하면 compile-time 오류가 발생합니다.

함수에서 매개 변수의 값을 수정하고 함수 호출이 종료된 후에도 변경 사항을 유지하려면 inout 파라미터를 사용하면 됩니다.

 

inout 키워드를 앞에 작성하면 됩니다.

inout 매개 변수는 함수에 전달된 값을 가지며 함수에 의해 수정되며 원래 값을 대체하기 위해 함수에 다시 전달됩니다.

 

var에만 inout 매개 변수로 전달할 수 있습니다.

상수 및 리터럴은 수정이 불가능하므로 인수로 전달할 수 없습니다.

변수 이름 앞에 앰퍼샌드(&)를 써서 수정될 수 있음을 나타냅니다.

 

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

swapTwoInts(_:_:)는 b와 a를 교체하는 함수입니다.

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"

 

 

참고

https://docs.swift.org/swift-book/LanguageGuide/Functions.html

 

Functions — The Swift Programming Language (Swift 5.4)

Functions Functions are self-contained chunks of code that perform a specific task. You give a function a name that identifies what it does, and this name is used to “call” the function to perform its task when needed. Swift’s unified function syntax

docs.swift.org

 

https://jcsoohwancho.github.io/2019-12-19-inout/

 

inout

이번 포스트에서는 Swift의 inout 매개변수에 대해서 알아보도록 하겠습니다. inout 매개변수란? Swift에서 함수와 메소드의 매개변수는 기본적으로 상수(Constant)로 전달이 되고, 해당 값을 직접 수정

jcsoohwancho.github.io

 

댓글
공지사항