Skip to content

Instantly share code, notes, and snippets.

@ole
Last active Oct 24, 2016
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@ole ole commented Sep 21, 2016

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