LoginSignup
3
3

More than 5 years have passed since last update.

【Objective-C】三項演算子を使って真偽型のif文をすっきり【Swift】

Last updated at Posted at 2016-08-19

三項演算子を使うことで真偽型のif文をすっきりできます。

値を入れる式 = 条件式 ? trueの場合 : falseの場合;

    BOOL isCheck;
    NSString *resultText;
    //Objective-CではBOOL型にYES,TRUE,1が使える
    isCheck = YES;   

if文だと

    if(isCheck){
        resultText = @"YES";
    }else if(!isCheck){
        resultText = @"NO";
    }

こうですが、三項演算子を使うと

    resultText = isCheck ? @"YES" : @"NO";

これだけでいいんです。
Swiftの場合は

var resultText : String?
var isCheck = false 

resultText = isCheck ? "YES" : "NO"
print(resultText!)

こんな感じです。
SwiftだとBoolの値はtrueかfalseしか使えないようです。

3
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
3
3