Skip to content

Commit 89784b8

Browse files
committed
add array chunk example
1 parent 49bd2ed commit 89784b8

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

bk1ch04p204arrays/bk1ch04p204collections/ViewController.swift

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,17 @@ class NoisyDogNOT : DogNOT {
2323
class Dog : NSObject {}
2424
class NoisyDog : Dog {}
2525

26+
// not in the book, just a useful extension I got off Stack Overflow http://stackoverflow.com/a/38156873/341994
27+
28+
extension Array {
29+
func chunked(by chunkSize: Int) -> [[Element]] {
30+
return stride(from: 0, to: self.count, by: chunkSize).map {
31+
Array(self[$0 ..< Swift.min($0 + chunkSize, self.count)])
32+
}
33+
}
34+
}
35+
36+
2637
class ViewController: UIViewController {
2738

2839
override func viewDidLoad() {
@@ -555,6 +566,13 @@ class ViewController: UIViewController {
555566
let cat2 = Cat()
556567
let ok = cat1 === cat2 // but `==` no longer compiles
557568
}
569+
570+
do {
571+
// using the array extension shown at the top
572+
let arr = [1,2,3,4,5]
573+
let chunked = arr.chunked(by: 2)
574+
print(chunked) // [[1, 2], [3, 4], [5]]
575+
}
558576

559577
}
560578

0 commit comments

Comments
 (0)