iOS - dropLast / popLast / removeLast

이한솔·2023년 8월 9일
0

iOS 앱개발 🍏

목록 보기
7/49
post-thumbnail

Swift에서 마지막 요소를 지우는 방법

1. dropLast()

마지막 요소를 제외한 나머지 요소의 시퀀스를 반환한다.

func dropLast(_ k: Int) -> Self.SubSequence

2. popLast()

컬렉션의 마지막 요소를 제거하고 반환한다.

mutating func popLast() -> Self.Element?

3. removeLast()

컬렉션의 마지막 요소를 제거하고 반환한다.

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


예시

var Array = [1, 2, 3, 4]
print(Array.dropLast(), Array) // Print [1, 2, 3] [1, 2, 3, 4]
print(Array.popLast()!, Array) // Print optional(4) [1, 2, 3]
print(Array.removeLast(), Array) // Print 4 [1, 2, 3]

dropLast()
Immutable, Array의 마지막 요소를 제외한 배열을 반환하고 기존 Array는 변경되지 않는다.
popLast() removeLast()
Mutable, 제거된 마지막 요소를 반환하고 해당 요소가 기존 Array에서 제거된다.


❓ popLast() 와 removeLast() 의 차이는?
popLast()는 옵셔널을 반환한다. 빈 배열에 popLast() 를 하면 nil 이 반환되지만 removeLast() 를 하면 컴파일 에러가 발생한다. 빈 배열인지 확인 후 removeLast() 를 사용하거나, popLast() 의 nil로 예외 처리를 해주면 된다.



dropLast() / dropFirst()

let str = "hello world!"

let dropStr = str.dropLast(1)
let firstDropStr = str.dropFirst(3)

print(dropStr) // 출력값 : hello world
print(firstDropStr) // 출력값 : lo world!

dropLast()로 문자열의 마지막 글자부터, dropFirst()로 앞 글자부터 지울 수 있다. 특정 개수를 지정해 줄 수도 있다.

3개의 댓글

comment-user-thumbnail
2023년 8월 9일

pop과 remove의 차이 배워갑니다.

답글 달기
comment-user-thumbnail
2023년 8월 9일

정리해주셔서 감사합니다!

답글 달기
comment-user-thumbnail
2023년 8월 9일

dropLast,popLast,removeLast의 정의와 차이점을 자세히 적어주셔서 감사합니다!

답글 달기