Removing objects from an array based on another array

前端 未结 9 1456
南方客
南方客 2021-02-05 01:14

I have two arrays like this:

var arrayA = [\"Mike\", \"James\", \"Stacey\", \"Steve\"]
var arrayB = [\"Steve\", \"Gemma\", \"James\", \"Lucy\"]

9条回答
  •  说谎
    说谎 (楼主)
    2021-02-05 01:27

    Original answer

    This can also be implemented as a minus func:

    func -( lhs:T, rhs:T ) -> T {
    
        var lhs = lhs
        for element in rhs {
            if let index = lhs.indexOf(element) { lhs.removeAtIndex(index) }
        }
    
        return lhs
    }
    

    Now you can use

    arrayA - arrayB
    

    Updated implementation for Swift 5

    func -(lhs: T, rhs: T) -> T where T.Iterator.Element: Equatable {
    
        var lhs = lhs
        for element in rhs {
            if let index = lhs.firstIndex(of: element) { lhs.remove(at: index) }
        }
    
        return lhs
    }
    

提交回复
热议问题