Swift equivalent to each_slice

前端 未结 3 349
轻奢々
轻奢々 2021-01-23 13:00

Is there something similar to Ruby\'s Enumerable#each_slice in Swift?

Ruby example:

arr = [\"a\", \"b\", \"c\", \"d\"]
arr.each_slice(2) {|s1, s2| puts s         


        
3条回答
  •  失恋的感觉
    2021-01-23 13:41

    Swift 4.1

    extension Array {
        /*
         [1,2,3,4,5].forEachSlice(2, { print($0) })
         => [1, 2]
         => [3, 4]
         => [5]
        */
        public func forEachSlice(_ n: Int, _ body: (ArraySlice) throws -> Void) rethrows {
            assert(n > 0, "n require to be greater than 0")
    
            for from in stride(from: self.startIndex, to: self.endIndex, by: n) {
                let to = Swift.min(from + n, self.endIndex)
                try body(self[from..

提交回复
热议问题