[Swift 코테 기초] reverse()와 reversed(), ReversedCollection<Array<Element>> 사용 방법

2023. 2. 22. 23:01Swift 코딩테스트/Swift 코테 기초

728x90

1. reverse()

  • reverse()는 새로운 배열을 리턴하지 않고 배열 그 자체를 변경한다.
var arr = [Int](1...10)
arr.reverse()
print(arr)    //[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

 

2. reversed()

  • reversed()는 컬렉션에서 역전된 순서의 요소를 새로운 뷰로 반환한다. 즉 원래 컬렉션의 값에는 변화가 없다.
  • A ReversedCollection instance wraps an underlying collection and provides access to its elements in reverse order
var arr = [Int](1...10)
arr.reversed()
print(arr)    //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

var a = arr.reversed()
print(a)      //ReversedCollection<Array<Int>>(_base: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

 

3. ReversedCollection<Array<Int>>(_base: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])에 접근하는 방법

print(a[0])    //Value of type '()' has no subscripts
  • 위와 같이 reversed()의 반환값에 접근하려고 하면 Value of type '()' has no subscripts 에러가 발생한다.
    • 이는 reversed()의 리턴 값인 ReversedCollection<Data>는 새로운 저장 공간을 할당받지 않고 역순으로 반복만 하는 방법이기 떄문이다.
    • You can reverse a collection without allocating new space for its elements by calling this reversed() method.
        • reversed()된 값에 접근하기 위해서는 mapping이 필요하다.
        • 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.
      var a = arr.reversed().map { $0 }
      print(a)      //[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
      print(a[0])   //10
      
      
      var b = Array(arr.reversed())
      print(b)      //[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
      print(b[0])   //10

 

 

 

 

 


https://stackoverflow.com/questions/70670936/no-exact-matches-in-call-to-subscript-reversed-array-in-swift

 

No exact matches in call to subscript, reversed array in Swift

I am trying to understand different Swift's basics better. I bumped on the reversed array concept in Paul Hudson's videos. He said that the array will be printed in the same order as the original o...

stackoverflow.com

https://developer.apple.com/documentation/foundation/data/2946831-reverse

 

Apple Developer Documentation

 

developer.apple.com

https://developer.apple.com/documentation/foundation/data/1780245-reversed

 

Apple Developer Documentation

 

developer.apple.com

 

728x90