RemoveAtIndex crash from swift array

后端 未结 5 706
半阙折子戏
半阙折子戏 2021-01-25 20:43

I have an array of letters, and want to match the characters against the letters and then do something to that letter (in this case turn it yellow) and then remove that matched

5条回答
  •  無奈伤痛
    2021-01-25 21:21

    So you have an array of Character(s):

    let letters = Array("randomness")
    

    An array of special Character(s)

    let specials = Array("ness")
    

    And you want to remove from letters, the specials right?

    Here it is:

    let set = Set(specials)
    let filtered = letters.filter { !set.contains($0) }
    
    filtered // ["r", "a", "d", "o", "m"]
    

    Update

    This version keep also consider the occurrences of a char

    let letters = Array("randomness")
    let specials = Array("ness")
    
    var occurrencies = specials.reduce([Character:Int]()) { (var dict, char) in
        dict[char] = (dict[char] ?? 0) + 1
        return dict
    }
    
    let filtered = letters.filter {
        if let num = occurrencies[$0] where num > 0 {
            occurrencies[$0] = num - 1
            return false
        } else {
            return true
        }
    }
    
    filtered // ["r", "a", "d", "o", "m", "n"]
    

提交回复
热议问题