씬디의 블로그
[Swift] .swapAt 배열 자리 바꾸기 본문
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
'App > Swift 문법' 카테고리의 다른 글
[Swift] 소수점 다루는 친구들(ceil, round, floor, trunc) (0) | 2023.12.01 |
---|---|
[Swift] 고차함수 filter (0) | 2023.12.01 |
[Swift] Partial Range From 범위에 관해서 (1) | 2023.11.30 |
[Swift] 고차함수 map (0) | 2023.11.30 |
[Swift] 삼항연산자 (1) | 2023.11.30 |