Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] ArraySlice, SubSequence 개념 본문

iOS 기본 (swift)

[iOS - swift] ArraySlice, SubSequence 개념

jake-kim 2022. 3. 15. 23:47

인덱싱으로 배열을 쪼갰을때 SubSequnce(=ArraySlice형)

let array = [1,2,3,4,5] // [Int]
let first = array[..<2] // Array<Int>.SubSequence
let second = array[2...] // Array<Int>.SubSequence

// Array<Int>.SubSequence == ArraySlice

ArraySlice와 SubSequence

  • ArraySlice는 본래의 array를 참조하고 있는 형태이므로, 새로운 메모리를 사용하지 않는 장점이 존재
  • 반면, 참조하고 있으므로 ArraySlice를 오랫동안 두게되면 memory leak이 발생할 수 있는 단점이 존재
  • Array와 동일한 인터페이스를 가지고 있으므로 사용하기 쉬운 장점이 존재

https://developer.apple.com/documentation/swift/arrayslice

  • SubSequence는 ArraySlice의 별칭

ArraySlice.swift

  • ArraySlice에서 주의할 점은 인덱스가 0부터 시작하지 않는 것을 주의
    • Index out of bounds 런타임 에러 주의
let array = [1,2,3,4,5] // [Int]
let first = array[..<2] // Array<Int>.SubSequence
let second = array[2...] // Array<Int>.SubSequence

print(first[0])
print(second[0]) // Fatal error: Index out of bounds

ArraySlice를 만든 이유

  • 사용할때의 편리성을 제공하고 따로 메모리 공간을 만들지 않는 최적화에 이점에 의하여 탄생
  • 하나의 배열이 있을 때 그 배열을 반으로 쪼개서, 각 배열의 합 중 어느것이 큰지 비교하는 경우? ArraySlice 사용하면 편리

ex) array 학점 배열이 있을 때 중간으로 쪼개서 왼쪽이 큰지 오른쪽이 큰지 비교

let scoreArray = [3.5, 4.0, 2.0, 4.5, 3.2, 4.3]
let mid = scoreArray.count / 2
let leftArraySum = scoreArray[..<mid].reduce(0, +)
let rightArraySum = scoreArray[mid...].reduce(0, +)

if leftArraySum < rightArraySum {
  print(left < right)
} else {
  print(left >= right)
}

* 참고

https://developer.apple.com/documentation/swift/arrayslice

Comments