Reputation: 131
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.
Upvotes: 9
Views: 8855
Reputation: 40965
I agree with the other answers that this is probably something best avoided, since the ternary operator's purpose is to evaluate to a value in both cases – you really just want an if
.
However, if you really want to do it, you can match the void return type of doSomethingIfTrue()
with ()
.
This isn’t generic across all possibilities though. If doSomethingIfTrue()
didn’t return void but instead returned an Int
, it wouldn’t work. You’d have to use 0
or something similar instead.
This will work (depending on your definition of work):
let pass: Any = ()
func doSomething() { }
func doSomethingElse() -> String { return "a" }
func doSomethingNumeric() -> Int { return 1 }
var num = 5
num > 5 ? doSomething() : pass
num > 5 ? doSomethingElse() : pass
num > 5 ? doSomethingNumeric() : pass
If you ever use the value returned by these expressions, they’ll be an Any
.
Don’t use this :-)
Upvotes: 1
Reputation: 535306
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.
Upvotes: 12
Reputation: 198344
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()
}
Upvotes: 1