티스토리 뷰

🍏/Swift

[Swift Algorithms] chunks(ofCount:)

eungding 2021. 9. 28. 12:09
반응형

swift-algorithms 패키지 / swift-collections 패키지  가 등장하면서

(참고: WWDC 2021 Meet the Swift Algorithms and Collections packages)

 

기존에 extension으로 만들어서 쓰고 있었던 chuck 메소드를 패키지 안의 메소드로 교체할 수 있게 되었습니다! 

 

[ as is ]

 

 import Foundation
 
 extension Array {
 
     // https://www.hackingwithswift.com/example-code/language/how-to-split-an-array-into-chunks
     public func chunked(into size: Int) -> [[Element]] {
        return stride(from: 0, to: count, by: size).map {
            Array(self[$0 ..< Swift.min($0 + size, count)])
        }
     }
 }

 

[ to be ] 

 

우선 swift-algorithms 패키지 를 SPM으로 추가해주셔야합니다. 

 

import Foundation
import Algorithms

extension Array {

    public func chunked(into size: Int) -> [[Element]] {
        return self.chunks(ofCount: size).map { Array($0) }
    }
}

 

 

[ 테스트  ]

 

  let array = [1, 2, 3, 4, 5, 6, 7, 8]
  
  // as is 
  print(array.chunked(into: 3)) 
  // [[1, 2, 3], [4, 5, 6], [7, 8]]
  
  // to be 
  print(array.chunks(ofCount: 3)) 
  // ChunksOfCountCollection<Array<Int>>(base: [1, 2, 3, 4, 5, 6, 7, 8], chunkCount: 3, endOfFirstChunk: 3)
  
  print(array.chunks(ofCount: 3).map { Array($0)}) 
  // [[1, 2, 3], [4, 5, 6], [7, 8]]

 

 

[ Complexity ] 

 

코드에 Complexity가 저렇게 적혀있는데 어떻게 읽어야할 지 모르겠네요,,,, 

 

https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Chunked.swift

 

 

주석 때문에 O(*n*) 로 된 것 같고 

옵션 키 눌러보면 O(n) 이라고 나옵니다!! 

 

 

 

반응형

'🍏 > Swift' 카테고리의 다른 글

[Swift] assert, precondition, fatalError  (1) 2021.12.05
[Swift] Self Type  (0) 2021.11.22
[Swift] async / await 사용사례  (0) 2021.07.06
[Swift] async / await 동작원리  (0) 2021.07.06
[Swift] async / await 등장배경  (0) 2021.06.30
댓글