Noah Noah - 14 days ago 6
Swift Question

EXC BAD ACCESS while creating a new 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#>


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?

Answer

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
    }
}
Comments