LoginSignup
0
1

More than 1 year has passed since last update.

【Swift】isEmptyの挙動メモ

Posted at

isEmptyを文字列や配列に使うことがあると思いますが、たまにごちゃっとなるのでメモします。
同じように「どうだったけ?」という方の参考になれば幸いです!

実行環境

Swift 5.4.2

nilがない場合

let case1 = ""
print(case1.isEmpty)
// true

let case2 = " "
print(case2.isEmpty)
// false

let case3 = [""]
print(case3.isEmpty)
// false

let case4 = [" "]
print(case4.isEmpty)
// false

let case5:[String] = []
print(case5.isEmpty)
// true

nilがある場合

let case1: String? = nil
print(case1?.isEmpty)  //warningが出ます
// nil

let case2: String? = nil
print(case2!.isEmpty)
// nilを強制アンラップするためクラッシュします

let temp: String? = nil
let case3 = [temp]
print(case3.isEmpty)
// false

let temp: String? = nil
let case4 = [temp, ""]
print(case4.isEmpty)
// false

let temp1: String? = nil
let temp2: String? = nil
let case5 = [temp1, temp2]
print(case5.isEmpty)
// false

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