2

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?

Noah
  • 1,329
  • 11
  • 21

1 Answers1

0

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
    }
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • This bug is https://bugs.swift.org/browse/SR-2503 and has been fixed in Foundation: https://github.com/apple/swift/pull/5201 and a fix is forthcoming for corelibs-foundation: https://github.com/apple/swift-corelibs-foundation/pull/680 – jtbandes Nov 20 '16 at 19:42