본문 바로가기
iOS/Swift배우기

[Swift] inout 파라미터

by 붕어사랑 티스토리 2024. 3. 20.
반응형

1. inout 파라미터란

 

스위프트는 기본적으로 함수 파라미터가 constant다. 함수 내에서 이 값을 바꾸려 하면 컴파일 에러가 난다.

 

그럼 스위프트에서 call by reference를 어떻게 하냐? inout 파라미터를 사용하면 가능하다.

 

inout 파라미터는 함수를 호출할 때 &를 붙여주어야 한다. C언어처럼

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"
반응형

'iOS > Swift배우기' 카테고리의 다른 글

[Swift] PropertyWrapper 사용법  (0) 2024.03.22
[SwiftUI] 자식에게 State 전달하기  (0) 2024.03.21
SwiftUI에서 {} 동작 원리  (0) 2024.03.20
[Swift] Generic이란  (0) 2024.03.20
[Swift] Protocol 배우기  (0) 2024.03.19

댓글