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
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")
}
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
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"
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.
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"
Swift 5 Easy One line Solution
var isSeller = (UserDefaults.standard.value(forKey: "isRole") as? String == "ROLE_SELLER") ? true : false
Swift 5 Easy Solution
let exercise = (segcExercise.selectedSegmentIndex == 0) ? "GymLover" : (segcExercise.selectedSegmentIndex == 1) ? "Occasionally" : "No Way"
//MARK:- outPut // Occasionally
{}
for all branches, but the parenthesis are optional()
, you can keep them if you'd like to.