NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

SOLVED: Easiest way to create an array of all capital letters?

Forums > Swift

Basically, I want to end up with the same result as this...

let letters = ["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"]

But I don't want to have to type out each letter in quotes individually. It seems like there must be a better way to do this right?


Well, it doesn't get much better than that. What you can do is:

let letters = "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"
let singleLetters = letters.components(separatedBy: ",")


Probably the easiest:

//["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"]


Alright thanks.

I was thinking there would be something like this that could be used

let letters = Array(CharacterSet.uppercaseLetters)

This doesn't work, and I'm not exactly sure why. But I thought there would at least be something similar to use.

Although, looking at roosterboy's solution, it's about the same amount of characters to type anyway.

But if there were something like this, you could use the auto completion in Xcode to type it faster, and not have to worry about if you mistyped the string.


This doesn't work, and I'm not exactly sure why. But I thought there would at least be something similar to use.

Because CharacterSet isn't a Collection. It's not really a Set, despite the name.

CharacterSet is designed for you to test membership (e.g., is a particular character in the Unicode group CharacterSet.uppercaseLetters), not for iterating through.

Also, if you look at the documentation for CharacterSet.uppercaseLetters, it is described as: "the characters in Unicode General Category Lu and Lt."

Category Lu contains 1,791 characters. Category Lt (also represented by CharacterSet.capitalizedLetters) contains an additional 31 characters. I'm not sure that's truly what you were looking for. ;)

You could assemble an array of uppercase ASCII letters by looping through the ASCII values 65 through 90, but you're still hardcoding something so I, at least, don't consider it much of an improvement over what I posted before.


Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.