씬디의 블로그

[Swift] .swapAt 배열 자리 바꾸기 본문

App/Swift 문법

[Swift] .swapAt 배열 자리 바꾸기

cyndi 2023. 12. 1. 21:53

Swift

배열 안에서 요소들의 위치를 바꿔야 할 때 .swapAt을 사용한다

var numbers = [2, 6, 4, 8]

// swap 6 and 4
numbers.swapAt(1, 2)

print(numbers) // [ 2, 4, 6, 8 ]

 

예제

for _ in 0..<m {
    let input = readLine()!.components(separatedBy: " ").map { Int($0)! }
    let i = input[0], j = input[1]
    basket.swapAt(i, j)
}

// i: 교환할 1번째 값의 인덱스
// j: 교환할 2번째 값의 인덱스

https://developer.apple.com/documentation/swift/array/swapat(_:_:)

 

swapAt(_:_:) | Apple Developer Documentation

Exchanges the values at the specified indices of the collection.

developer.apple.com