In Swift, an efficient function that separates an array into 2 arrays based on a predicate

后端 未结 7 1073
太阳男子
太阳男子 2020-12-15 04:40

Note: I\'m currently still using Swift 2.2, but open to Swift 3 solutions as well

I\'m looking to create a function that operates very closely to filter

相关标签:
7条回答
  • 2020-12-15 05:19
    // swap and return pivot
    extension Array
    {
        // return pivot
        mutating func swapIf(predicate: (Element) -> Bool) -> Int
        {
            var pivot = 0
            for i in 0..<self.count
            {
                if predicate( self[i] )
                {
                    if i > 0
                    {
                        swap(&self[i], &self[pivot])
                    }
    
                    pivot += 1
                }
            }
    
            return pivot
        }
    }
    

    This is my code and the concept is.. reduce memory usage.

    I checked that 'swapIf' is 4-times faster than 'removeIf'.

    0 讨论(0)
提交回复
热议问题