Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do nothing in If inside swift

Tags:

swift

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.

like image 419
sweekim Avatar asked Dec 26 '14 01:12

sweekim


People also ask

How do you break an if statement in Swift?

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.

How do you tell a code to do nothing?

Answer: use _ = 0 .

What does != Mean in Swift?

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 .

What is #if in Swift?

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.


2 Answers

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.

like image 51
matt Avatar answered Sep 18 '22 07:09

matt


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()
}
like image 41
Amadan Avatar answered Sep 19 '22 07:09

Amadan