47

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 
2
  • 7
    Unlike Objective C, braces are mandatory while using if statements in Swift. The reason behind this is to make the code safer.
    – ZeMoon
    Jun 11, 2014 at 9:01
  • you have to add the braces {} for all branches, but the parenthesis are optional (), you can keep them if you'd like to.
    – holex
    Jun 11, 2014 at 12:59

8 Answers 8

64

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")
}
48

In Swift the braces aren't optional like they were in Objective-C (C). The parens on the other hand are optional. Examples:

Valid Swift:

if someCondition {
    // stuff
}

if (someCondition) {
    // stuff
}

Invalid Swift:

if someCondition 
    // one liner

if (someCondition)
    // one liner

This design decision eliminates an entire class of bugs that can come from improperly using an if statement without braces like the following case, where it might not always be clear that something's value will be changed conditionally, but somethingElse's value will change every time.

Bool something = true
Bool somethingElse = true

if (anUnrelatedCondition) 
    something = false
    somethingElse = false

print something // outputs true
print somethingElse // outputs false
3
  • 7
    One example of a widely publicized bug which is related to this, is Apple's SSL/TLS bug, while Swift was in development. I sometimes wonder if this design decision was made because of that, or if it's just coincidental. It's an interesting detail of Swift, since it's very uncommon for "C like" languages to enforce a coding style.
    – Jonas
    Feb 5, 2015 at 12:29
  • Apple's SSL/TLS bug - doesn't indicate that single line If's are the problem. It clearly shows that CMD+V should not use "Key-delay" and "key-repeat" setting of keyboard and should paste only once. Try copying one line of text and press CMD+V a little longer than usual. That's unless, developer purposely put two consecutive "goto fail;" assuming to work in a single if block, to make sure that if in case the control pointer does not obey the first time, repeating a second time would help. "You still here ???? I have already told you to goto fail.... GOTO FAIL this instant !!!" Aug 2, 2016 at 19:10
  • You can't put parenthesis around if let statements. Nov 30, 2017 at 22:36
31

You can use new Nil-Coalescing Operator, since Swift 3 in case when you need just set default value in case of if fails:

let someValue = someOptional ?? ""

In case if someOptional is false, this operator assign "" to someValue

var dataDesc = (value == 7) ? "equal to 7" : "not equal to 7"
16

One-line if, one-line while and one-line for are considered a bad style by many developers because they are less readable and allegedly a source of many errors.

Swift solved the conundrum by forbidding one-line flow control statements; the braces are non-optional...

if someCondition {
     // stuff
}

Of course, you can still do

if someCondition { return }

There are also implementation reasons. Having the parentheses around the condition as optional makes the parsing much harder. Enforcing braces simplifies parsing again.

1
  • "Alleged" is about right. With conventions such as consistent use of Allman braces and indentation, it was already very preventable. Jul 26, 2014 at 1:45
12

Here is a simple solution I used in my projects.

Swift 4+

isManageCardTnCSelected ?
      (checkbox.isSelected = true) : (checkbox.isSelected = false)

var selected: Bool = isManageCardTnCSelected ?
      checkbox.isSelected = true : checkbox.isSelected = false

Swift 3+

var retunString = (state == "OFF") ? "securityOn" : "securityOff"
0
0

One line solution for Swift 3+

isMyVar ? someAction() : ()
0

Swift 5 Easy One line Solution

var isSeller = (UserDefaults.standard.value(forKey: "isRole") as? String == "ROLE_SELLER") ? true : false
1
  • 1
    I think swift conventions says to not use parenthesis on if statements Oct 7, 2021 at 15:58
0

Swift 5 Easy Solution

let exercise = (segcExercise.selectedSegmentIndex == 0) ? "GymLover" : (segcExercise.selectedSegmentIndex == 1) ? "Occasionally" : "No Way"

//MARK:- outPut   // Occasionally

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.