LoginSignup
1
3

More than 3 years have passed since last update.

Optionalの比較

Posted at

オプショナルの比較

オプショナルの値の比較

オプショナル変数を比較する場合、unwarpする必要がある

 var i: Int?
 if let i = i {
    if i == 0 {
        print("0")
    } else {
        print("0ではない")
    }
 } else {
    print("nil")
 }

もちろんすべてのケースでそれぞれ処理する必要があるなら別だが、1以上の場合のみラベルを表示するとかになると
let isHidden = i > 0
だけで良い

比較2

String?の.countやisEmpty の場合

こちらも基本同じです。

func hoge2(_ val: String?) {
    if val?.count == 0 {
        print("0文字です")
    }
    if val?.isEmpty == true {
        print("0文字です2")
    }
    if varl?.isEmpty == false {
        print("0文字じゃないかnilです")
    }
}
hoge2("1")
print("^^^^ \"1\"の結果 ^^^^")
hoge2("")
print("^^^^ \"\"の結果 ^^^^")
hoge2(nil)
print("^^^^ nilの結果 ^^^^")

結果

文字列がある =  1
^^^^ "1"の結果 ^^^^
0文字です
0文字です2
^^^^ ""の結果 ^^^^
^^^^ nilの結果 ^^^^
1
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
1
3