Michel Michel - 7 months ago 55
Swift Question

Trying to define a custom NSCharacterSet with unicode characters in Swift

I want to define in Swift an

containing: [A-Z] (note the double-bytes, this is not [A-Z]).

What is the proper syntax to do that? The code below that I had working in Objectiv C doesn't seem to translate to Swift so easily.'

NSRange alphaDoubleByteRange;
NSMutableCharacterSet *alphaDoubleByteLetters;
alphaDoubleByteRange.location = (unsigned int)[@"A" characterAtIndex:0];
alphaDoubleByteRange.length = 26;
alphaDoubleByteLetters = [[NSMutableCharacterSet alloc] init];
[alphaDoubleByteLetters formUnionWithCharacterSet:[NSCharacterSet characterSetWithRange:alphaDoubleByteRange]];
// Now alphaDoubleByteLetters contains what I want.


You can create a character set from the range of the unicode scalar values:

let firstCode = Int("A".unicodeScalars.first!.value)
let lastCode =  Int("Z".unicodeScalars.first!.value)
let alphaDoubleByteRange = NSRange(location: firstCode, length: lastCode - firstCode + 1)
let alphaDoubleByteLetters = NSCharacterSet(range: alphaDoubleByteRange)

Alternatively, lookup the characters in a Unicode table and use the scalar values directly:

let firstCode = 0xFF21  // "A"
let lastCode =  0xFF3A  // "Z"
// ...