Creating own character set causes crash

167 Views Asked by At

I'm using this piece of code to limit user input regarding the keyboard.

 func textField(_ textField: UITextField, shouldChangeCharactersIn     range: NSRange, replacementString string: String) -> Bool {
    let allowedCharacters = CharacterSet.init(charactersIn: ".0123456789")
    let characterSet = NSCharacterSet(charactersIn: string)

    return allowedCharacters.isSuperset(of: characterSet as CharacterSet)
}

but my program crashes when I enter any character. enter image description here

Update 2: So 99.9% of this solution works great, unfortunately the period/decimal point does not register. Unsure why this is happening?

1

There are 1 best solutions below

4
b_ray On

This appears to be a bug in Swift, there are multiple issues on this matter on the Swift issue tracker: https://bugs.swift.org/browse/SR-3311, https://bugs.swift.org/browse/SR-3667

Until this has been fixed, you can workaround this problem by using the following extension:

extension CharacterSet {

    func isSupersetOf(other: CharacterSet) -> Bool {
        return CFCharacterSetIsSupersetOfSet(self as CFCharacterSet, (other as NSCharacterSet).copy() as! CFCharacterSet)
    }
}

Keep in mind that you need to change your characterSet variable from type NSCharacterSet to CharacterSet to be able to use that extension in your example.