LoginSignup
0
1

More than 1 year has passed since last update.

【Swift】文字列を比較する

Posted at

はじめに

文字列を比較する方法を学んだので記録しておきます。

使い方

import Foundation
let A = "123"

let B = "456"

let compare = A.compare(B, options: .numeric)

switch compare {
case .orderedAscending:
    print("Aの方が小さいです")
case .orderedDescending:
    print("Aの方が大きいです")
case .orderedSame:
    print("AとBは同じです")
}

解説

数字と数字の比較ならわかりやすいですね
しかし、compareは数字以外も比較できます。

なぜ数字以外が比較できるのでしょうか
どのようなルールで比較してるのでしょうか

これは文字列の順序が上か下か同じかを判定しているものであると思います。

よって、数字とひらがなであっても比較できます。

数字 < アルファベット(大) < アルファベット(小) < ひらがな < カタカナ
数字
1 < ... < 9

アルファベット(大)
A < ... < Z

アルファベット(小)
a < ... < z

ひらがな
あ < ... < ん

カタカナ
ア < ... < ン

おわり

不思議だったので調べてみました
もし間違ってたらコメントください

0
1
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
0
1