EXC BAD ACCESS while creating a new CharacterSet

社会主义新天地 提交于 2019-12-11 04:29:45

问题


I'm trying to write a slugging function which involves stripping out any punctuation characters except for hyphens. I thought the best way to do this would be to create a new CharacterSet as follows:

import Foundation

extension CharacterSet {

    func subtracting(charactersIn string: String) -> CharacterSet {
        let unwantedCharacters = CharacterSet(charactersIn: string)
        return self.subtracting(unwantedCharacters)
    }


}

let punctuationCharactersExcludingHyphen = CharacterSet.punctuationCharacters.subtracting(charactersIn: "-")

<#slug function using punctuationCharactersExcludingHyphen#>

where slug function is a function that I've already tested with existing character sets. The problem is that the assignment let punctuationCharactersExcludingHyphen... crashes with a EXC_BAD_ACCESS code=2.

I've noticed that most problems involving this error are caused by some specific syntax error or the like, but I can't find out what it is here. Any ideas?


回答1:


That looks like a bug to me. Building the difference of any two CharacterSets results in an "infinite" recursion and a stack overflow. Here is a minimal example which causes the crash:

let cs1 = CharacterSet.punctuationCharacters
let cs2 = CharacterSet.decimalDigits
let cs = cs1.subtracting(cs2)

A workaround is to use the

public mutating func remove(charactersIn string: String)

method of CharacterSet instead:

var punctuationCharactersExcludingHyphen = CharacterSet.punctuationCharacters
punctuationCharactersExcludingHyphen.remove(charactersIn: "-")

or if you want an extension method:

extension CharacterSet {
    func subtracting(charactersIn string: String) -> CharacterSet {
        var cs = self
        cs.remove(charactersIn: string)
        return cs
    }
}


来源:https://stackoverflow.com/questions/40702492/exc-bad-access-while-creating-a-new-characterset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!