5
3

More than 3 years have passed since last update.

「"A"..."Z"」でアルファベットの配列を取得する

Last updated at Posted at 2019-12-07

経緯

勉強のコードを動かしてると理解が合ってるか確認するためにA~Zの文字をループで回して試したくなることがあって

func hoge(_ v:String){
 //ここで書いた処理が合ってるか試したい
}

let test = "ABCDEFGHIJKLMNOPQRSTUVWXWZ" // <- なんかめんどい
for c in test{
  hoge(c)
}
for c in "A"..."Z"{ // <- こうしたい
  hoge(c)
}

C言語の時ならchar型に++でループさせてたなあ...

やってみた

Stirng+extension.swift
infix operator ...
extension String{
    static func ...(left: String, right: String) ->Array<Character> {
        return ((left.unicodeScalars.first!.value) ... (right.unicodeScalars.first!.value)).map { Character(UnicodeScalar($0)!) }
    }
}
test.swift
let alphabets = ("a"..."z") + ("A"..."Z")
print(alphabets)
/*
["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",
"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"]
*/

1...10と違ってClosedRange型じゃないけど...

結論

unicodeScalarsって初めて知ったよ

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3