본문 바로가기
iOS/애플 개발자 공식 문서

[Swift] reversed로 컬렉션 타입의 순서를 뒤집는 뷰 반환하기

by Dev.Andy 2023. 4. 7.

프로그래머스에서 자연수를 뒤집어 배열로 만드는 문제를 풀다가 reversed() 메서드를 알게 되었다. 이를 정리해 보기 위해 이번 포스팅을 하게 되었다.

 

아래의 공식 문서를 참고 했다.

 

📌 정의 

  Returns a view presenting the elements of the collection in reverse order.
  컬렉션의 요소를 반대 순서로 표시하는 뷰(view)를 반환한다.

여기서 중요한 것은 단순히 반대 순서로 만드는 게 아니라 이를 표시하는 뷰를 반환하는 것이다. 따라서 다시 그 컬렉션을 원하면 메서드를 사용한 이후 형 변환을 해야 한다.

 

📌 선언

func reversed() -> ReversedCollection<Self>

반환하는 자료형이 신기하게 ReversedCollection이다.

 

📌 논의

  You can reverse a collection without allocating new space for its elements by calling this reversed() method. A ReversedCollection instance wraps an underlying collection and provides access to its elements in reverse order. This example prints the characters of a string in reverse order:
  이 reversed() 메서드를 호출함으로써 컬렉션의 요소를 새 공간에 할당할 필요 없이 순서를 뒤집을 수 있다. ReversedCollection 인스턴스는 주어진 컬렉션을 래핑하고 컬렉션의 요소를 역순으로 접근하는 것을 제공한다. 아래의 예제에서는 문자열의 문자를 역순으로 출력한다.
let word = "ReversedCollection"
for char in word.reversed() {
    print(char, terminator: "") // noitcelloCdesreveR
}

 

word.reversed()의 자료형은 ReversedCollection이다.

print(word.reversed()) // ReversedCollection<String>(_base: "ReversedCollection")
print(type(of: word.reversed())) // ReversedCollection<String>

 

  If you need a reversed collection of the same type, you may be able to use the collection’s sequence-based or collection-based initializer. For example, to get the reversed version of a string, reverse its characters and initialize a new String instance from the result.
  동일한 자료형의 역순의 컬렉션이 필요하면, 컬렉션의 시퀀스 기반이나 컬렉션 기반의 이니셜라이저를 사용할 수 있다. 예를 들어, 문자열의 역순을 구하기 위해서는 결과물로부터 새 문자열 인스턴스를 초기화하면 된다.
let reversedWord = String(word.reversed())
print(reversedWord) // noitcelloCdesreveR

ReversedCollection을 다시 이니셜라이저를 이용하여 원하는 컬렉션의 자료형으로 다시 바꿔 주어야 한다.

 

📌 복잡도

$O(1)$

댓글