Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single line if statement in Swift

How would one convert the following to Swift from Objective-C?

if (myVar) return; 

Swift does not use parentheses around the conditional, however the following code gives an error.

if myVar return  
like image 758
BytesGuy Avatar asked Jun 11 '14 08:06

BytesGuy


People also ask

What does ~= mean in Swift?

The expression represented by the expression pattern is compared with the value of an input expression using the Swift standard library ~= operator. The matches succeeds if the ~= operator returns true . By default, the ~= operator compares two values of the same type using the == operator.

What is ternary operator Swift?

Ternary Operator in Swift A ternary operator evaluates a condition and executes a block of code based on the condition. Its syntax is condition ? expression1 : expression2. Here, the ternary operator evaluates condition and. if condition is true, expression1 is executed.


1 Answers

Well as the other guys also explained that braces are a must in swift. But for simplicity one can always do something like:

let a = -5  // if the condition is true then doThis() gets called else doThat() gets called a >= 0 ? doThis(): doThat()  func doThis() {     println("Do This") }  func doThat() {     println("Do That") } 
like image 158
4aRk Kn1gh7 Avatar answered Sep 21 '22 13:09

4aRk Kn1gh7