I am wondering inside of a if
statement, can I have something like Python pass
?
var num = 10
num > 5 ? doSomethingIfTrue(): doSomethingIfFalse()
The above code will be alright if both true and false methods are supplied. What if I only wanna to execute just the true method?? Such as:
num > 5 ? doSomethingIfTrue(): ***pass***
I am hoping to have something like a pass
statement in swift so the program will just carry on if false is return. I have tried continue
and fallthrough
but I guess they are only used inside a loop statement.
Explanation: In the above example, we have two for-in loops now we use the break statement inside the inner for-in loop that is “if i == 2 {break}”. Here, when the value of i is 2, the break statement terminates the inner loop and the control flow of the program moves to the outer loop and continues.
Answer: use _ = 0 .
Types that conform to the Equatable protocol can be compared for equality using the equal-to operator ( == ) or inequality using the not-equal-to operator ( != ). Most basic types in the Swift standard library conform to Equatable .
Swift if Statement The if statement evaluates condition inside the parenthesis () . If condition is evaluated to true , the code inside the body of if is executed. If condition is evaluated to false , the code inside the body of if is skipped.
You could, in theory, say this:
var num = 10
num > 5 ? doSomethingIfTrue() : ()
That works because ()
is a void statement.
But I wouldn't do that! I would write it this way:
var num = 10
if num > 5 { doSomethingIfTrue() }
Yes, it's more characters, but that's Swift; you can't omit the curly braces from an if construct. And your ternary operator was the wrong operator to start with. As someone else has pointed out, it really is most appropriate for conditional assignment and similar.
Really, it's a matter of adapting yourself to the syntax, operators, and flow control of this language. Don't to try to make Swift be like Python; it won't be.
The ?:
conditional operator expects a value in each of its three operands, because it needs to give a value back. Say you have the hypothetical
a = b + ((c > 0) ? 1 : pass)
What would you expect the +
to do if c
was not positive?
For statements, use if
as follows:
if num > 5 {
doSomethingIfTrue()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With