Warning: Undefined array key 2 in /home/naoooooo8/naoya-ono.com/public_html/swift/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 15
Warning: Undefined array key 3 in /home/naoooooo8/naoya-ono.com/public_html/swift/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 18
Warning: Undefined array key 4 in /home/naoooooo8/naoya-ono.com/public_html/swift/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 21
Warning: Undefined array key 2 in /home/naoooooo8/naoya-ono.com/public_html/swift/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 27
Warning: Undefined array key 3 in /home/naoooooo8/naoya-ono.com/public_html/swift/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 30
Warning: Undefined array key 4 in /home/naoooooo8/naoya-ono.com/public_html/swift/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 33
文字列の空判定。
どのようにやってますか? まさか文字列と「””」を比較してないですよね?
このページでは可読性の高い書き方と、あまりよくない書き方を紹介します。
可読性が高い書き方
一番良いのはisEmptyプロパティを使って判定する方法です。
名前からも分かるとおり「isEmpty」つまり 「空です」って書いてあるので、文字列が空かどうかはこれを使うのがベストでしょう。
結果はBool値で返ってくるので、trueなら空、falseなら、空じゃないということになります。
import UIKit
var str = ""
if str.isEmpty {
print("空です")
}else {
print("空じゃありません")
}
実際に、動作を確認するときちんと空判定できていることがわかります。
空の場合

空じゃない場合

空文字判定できるけど、あまりよくない書き方
以下の方法でも文字列の空判定はできますが、可読性を考えるとisEmptyを使ったほうが良いでしょう。
var str = ""
if str == "" {
print("空です")
}
if str.count == 0 {
print("空です")
}



