[iOS] removeLast() vs. popLast()

Eugenie·2022년 7월 14일
0

두 메서드는 공통적으로 배열의 마지막 요소를 없애고
없앤 값을 리턴한다.

removeLast()

@discardableResult mutating func removeLast() -> Self.Element

🥏 Return Value : 컬렉션의 마지막 요소

popLast()

mutating func popLast() -> Self.Element?

🥏 Return Value : 컬렉션의 마지막 요소

❗️ 컬렉션이 비어있다면 nil return

removeLast() vs. popLast()

removeLast()값이 무조건 존재해야하고,
popLast()값이 없으면 nil 을 리턴한다.

removeLast()

// example1. removeLast()
var nums = [5, 8]

let a = nums.removeLast() // nums = [5]
let b = nums.removeLast() // nums = []
let c = nums.removeLast() // Error

print(a) // 5
print(b) // 8
print(c)

print(nums)

변수 nums 는 2 개의 요소가 들어있는 배열이다.
removeLast() 를 이용하여 마지막 요소를 두 번 삭제하면
변수 nums 는 비어있는 상태가 될 것이다.

다음은 비어있는 배열에 removeLast() 를 이용하여
마지막 요소를 삭제하도록 했을 때 발생하는 에러이다.

Thread 1: Fatal error: Can't remove last element from an empty collection

popLast()

// example2.popLast()
var nums = [5, 8]

let a = nums.popLast() // nums = [5]
let b = nums.popLast() // nums = []
let c = nums.popLast()

print(a) // Optional(5)
print(b) // Optional(8)
print(c) // nil

print(nums) // []

removeLast() 에서 다룬 예시에서 popLast() 로만 변경해주었다.
removeLast() 와는 달리,
변수 nums 가 비어있는 상태일 때 popLast()nil 을 리턴해주었다.

❗️ 확실하게 배열의 값이 존재한다면 removeLast() 사용해도 되지만, nil 일 수 있다면 popLast() 를 사용하는 것이 더 안전하다.

📚 Reference
removeLast()
popLast()
Swift Array 배열 값 제거방법 removeLast, removeFirst
[Swift] removeLast(), popLast() 차이점

profile
🌱 iOS developer

0개의 댓글