Skip to content

Instantly share code, notes, and snippets.

@ole
Last active June 11, 2023 10:13
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ole/d5189f20840c52eb607d5cc531e08874 to your computer and use it in GitHub Desktop.
Save ole/d5189f20840c52eb607d5cc531e08874 to your computer and use it in GitHub Desktop.
Two options for converting character ranges into arrays
// We can't use `Character` or `String` ranges directly because they aren't countable
// Create a countable range of ASCII values instead
let range = UInt8(ascii: "a")...UInt8(ascii: "z") // CountableClosedRange<UInt8>
// Convert ASCII codes into Character values
range.map { Character(UnicodeScalar($0)) } // Array<Character>
// → ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
// Create a sequence of UnicodeScalar values from "a" to "z"
let seq = sequence(first: UnicodeScalar("a")!) { scalar in
guard scalar < UnicodeScalar("z")! else { return nil }
return UnicodeScalar(scalar.value + 1)!
}
// Convert UnicodeScalars to strings
seq.map { String($0) } // Array<String>
// → ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
@ole
Copy link
Author

ole commented Sep 21, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment