arr.split(where:)

ๆญคๆ–นๆณ•ๆœƒไบค็”ฑ where: ๅƒๆ•ธไพ†ๅˆคๆ–ท๏ผšใ€ŒๅŽŸ้™ฃๅˆ—ไธญ๏ผŒๅ‰ๅพŒๅ…ฉๅ…ƒ็ด ไน‹้–“่ฉฒไธ่ฉฒๆ–ท้–‹๏ผŒๅฝขๆˆๆ–ฐ็š„ๅญ้™ฃๅˆ—ใ€ใ€‚

๐Ÿ’ˆ็ฏ„ไพ‹๏ผš

let array = [1, 2, 2, 2, 3, 4, 4]

// โญ๏ธ equivalent to: `array.split { $0 != $1 }`
array.split(where: !=)    // [[1], [2, 2, 2], [3], [4, 4]]

๐Ÿ’พ ็จ‹ๅผ๏ผš

// โญ๏ธ arr.split(where:)
extension Array {
    
    /// split an array into array of subarrays.
    public func split(
        where shouldSplit: (Element, Element) -> Bool
    ) -> [[Element]] 
    { 
        // result of splitting (array of subarrays)
        var result: [[Element]] = isEmpty ? [] : [[self[0]]]
        
        // for each (previous, current) pair
        for (previous, current) in zip(self, self.dropFirst()) { 
            // if should split, 
            if shouldSplit(previous, current) {
                // append new subarray
                // --------------------
                result.append([current])     
            } else {
                // else append to the last subarray.
                // -----------------------------------
                // ๐Ÿงจ Note: 
                //   don't use `result.last` to append,
                //   the `last` property is immutableโ—๏ธ 
                result[result.endIndex-1].append(current)
            }
        } 
        
        return result
    }
}

Last updated