问题描述
我正在尝试编写一个功能强大的函数,其中涉及去除连字符以外的所有标点符号.我认为最好的方法是创建一个新的CharacterSet,如下所示:
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#>
其中slug function是我已经使用现有字符集测试过的功能.问题是赋值let punctuationCharactersExcludingHyphen...与EXC_BAD_ACCESS code=2崩溃.
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?
推荐答案
对我来说,这似乎是个错误.建立两个 any 的区别CharacterSet导致无限"递归和堆栈溢出.这是导致崩溃的最小示例:
That looks like a bug to me. Building the difference of any twoCharacterSets 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)
一种解决方法是使用
public mutating func remove(charactersIn string: String)
CharacterSet的方法:
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 } }
这篇关于创建新的CharacterSet时执行EXC不良访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!