Skip to content

Instantly share code, notes, and snippets.

@sharplet
Last active April 27, 2021 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sharplet/62458bd179353d78c0e8e8b7a1c435b0 to your computer and use it in GitHub Desktop.
Save sharplet/62458bd179353d78c0e8e8b7a1c435b0 to your computer and use it in GitHub Desktop.
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