Skip to content

Instantly share code, notes, and snippets.

@sharplet sharplet/scalars.swift
Last active Apr 7, 2017

Embed
What would you like to do?
Swift program to print out all the unicode scalars in a Foundation CharacterSet.
// Prints out all the unicode scalars in a Foundation CharacterSet.
//
// Compile: swiftc -O scalars.swift
// Run: ./scalars <character set name>
import Foundation
extension UnicodeScalar {
static var allScalars: AnySequence<UnicodeScalar> {
let numbers = sequence(first: 0, next: { $0 + 1 })
let scalars = numbers
.lazy
.prefix(while: { $0 < 0xFFFF })
.flatMap(UnicodeScalar.init)
return AnySequence(scalars)
}
}
extension CharacterSet {
static func named(_ string: String) -> CharacterSet? {
let name = string
.replacingOccurrences(of: "Characters$", with: "CharacterSet", options: .regularExpression)
.replacingOccurrences(of: "s$", with: "CharacterSet", options: .regularExpression)
let klass = NSCharacterSet.self as AnyObject
let selector = Selector(name)
guard klass.responds(to: selector) else { return nil }
return (klass.perform(selector).takeUnretainedValue() as! CharacterSet)
}
}
func usage(_ message: String) -> Never {
fail(
"\(message)\n"
+ "\n"
+ "See the 'Type Properties' section of https://developer.apple.com/reference/foundation/characterset\n"
+ "for a list of character set names."
)
}
func fail(_ message: String) -> Never {
fputs("\(message)\n", stderr)
exit(1)
}
guard case let arguments = CommandLine.arguments.dropFirst(),
let characterSetName = arguments.first
else { usage("Please specify a character set name.") }
guard let characterSet = CharacterSet.named(characterSetName)
else { usage("No character set found with name '\(characterSetName)'.") }
for scalar in UnicodeScalar.allScalars where characterSet.contains(scalar) {
print(scalar, terminator: "")
}
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.