Last active
June 11, 2023 10:13
-
-
Save ole/d5189f20840c52eb607d5cc531e08874 to your computer and use it in GitHub Desktop.
Two options for converting character ranges into arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also check out @natecook1000's solution: making
UnicodeScalar
conform toStrideable
.