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

后端 未结 7 1101
太阳男子
太阳男子 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:02

    Swift 4 Solution

    partition(by:)

    It reorders the origin array and returns start index of subarray satisfies the predicate.

    In this example it returns 7.

    0..<7 elemets aren't divisible by 3 and 7..n-1 elements are divisible by 3.

     var numbers = [1,2,3,4,5,6,7,8,9,10]
     let partition = numbers.partition(by: { $0 % 3 == 0 })
     let divisibleBy3 = Array(numbers[..

提交回复
热议问题