swift if or/and statement like python
You can use
&&
for logical and
||
for logical or
so you can do
if a > 0 && i == j || f < 3 {
...
}
see here
https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/BasicOperators.html
Python style conditional expression in Swift 3
Great question :)
Rather than storing the expression, store the result as an optional if the conditional is false. Edited based on some comments, resulting in some much cleaner code.
infix operator ==| : TernaryPrecedence // if/where
infix operator |!= : TernaryPrecedence // else
func ==|<T> (lhs: @autoclosure () -> T, rhs: T?) -> T {
return rhs ?? lhs()
}
func |!=<T> (lhs: Bool, rhs: @autoclosure () -> T) -> T? {
return lhs ? nil : rhs()
}
Swift if statement - multiple conditions separated by commas?
Yes when you write
if let a = optA, let b = optB, let c = optC {
}
Swift does execute the body of the IF
only if all the optional bindings are properly completed.
More
Another feature of this technique: the assignments are done in order.
So only if a value is properly assigned to a
, Swift tries to assign a value to b
. And so on.
This allows you to use the previous defined variable/constant like this
if let a = optA, let b = a.optB {
}
In this case (in second assignment) we are safely using a
because we know that if that code is executed, then a
has been populated with a valid value.
If an if statement gets called and all the conditions are true, do all the else if statements get called also?
No, and you can visualize it like this:
if coins > 19 && speedLvl == 1 {
speedLvl = 2
coins = coins - 20
}
else {
if coins > 49 && speedLvl == 2 {
speedLvl = 3
coins = coins - 50
}
else {
if coins > 99 && speedLvl == 3 {
speedLvl = 4
coins = coins - 100
}
}
}
Although this code would be more easily written in Swift 4 as:
switch (speedLvl, coins) {
case (1, 20..<50):
speedLvl += 1
coins -= 20
case (2, 50..<100):
speedLvl += 1
coins -= 50
case (3, 100...):
speedLvl += 1
coins -= 100
default: break;
}
or better yet, perhaps:
let levelUpCosts = [0, 20, 50, 100]
let levelUpCost = levelUpCosts[speedLvl]
if levelUpCost < coins {
coins -= levelUpCost
speedLvl += 1
}
If you want to multiple level ups to be possible, all in one shot, then you can do something like this:
let levelUpCosts = [0, 20, 50, 100]
var affordedLevelUpsCost = 0
let affordedLevelUps = levelUpCosts.lazy.prefix(while: { cost in
let newCost = affordedLevelUpsCost + cost
let canAffordLevelUp = newCost < coins
if canAffordLevelUp { affordedLevelUpsCost = newCost }
return canAffordLevelUp
})
speedLvl += affordedLevelUps.count
coins -= affordedLevelUpsCost
Can I use the OR operator or AND operator between two if..else statement?
Combine them into one statement like this:
if age < 30 AND height_feet > 6.1 then
' do something
else
' do something else
end if
If you have to check the OR condition, just switch the AND to OR.
EDIT
You can combine if statements like this also:
if age < 30 AND height_feet > 6.1 then
' do something
else if age < 30 OR height_feet > 6.1 then
' do something
else
if employee_type = 1 then
' do something
else
' do something
end if
end if
Swift equivalent for while loops with else in python
There is no while ... else ...
in Swift, you will have to refactor your logic.
Also, you do not want to loop inside touchesBegan
your app will stop responding!
Can I use the range operator with if statement in Swift?
You can use the "pattern-match" operator ~=
:
if 200 ... 299 ~= statusCode {
print("success")
}
Or a switch-statement with an expression pattern (which uses the pattern-match
operator internally):
switch statusCode {
case 200 ... 299:
print("success")
default:
print("failure")
}
Note that ..<
denotes a range that omits the upper value, so you probably want200 ... 299
or 200 ..< 300
.
Additional information: When the above code is compiled in Xcode 6.3 with
optimizations switch on, then for the test
if 200 ... 299 ~= statusCode
actually no function call is generated at all, only three assembly instruction:
addq $-200, %rdi
cmpq $99, %rdi
ja LBB0_1
this is exactly the same assembly code that is generated for
if statusCode >= 200 && statusCode <= 299
You can verify that with
xcrun -sdk macosx swiftc -O -emit-assembly main.swift
As of Swift 2, this can be written as
if case 200 ... 299 = statusCode {
print("success")
}
using the newly introduced pattern-matching for if-statements.
See also Swift 2 - Pattern matching in "if".
How does Swift handle if statements?
Yes
When you concatenate a list of conditions C[0]
...C[n]
with the AND &&
operator, the runtime evaluates in order each condition and if a C[i]
condition is found false
, then the evaluation of the whole expression does end and it is judged false
.
let c0 = true
let c1 = false
let c2 = true
if c0 && c1 && c2 {
print("Hello world")
}
In this case only c0
and c1
will be evaluated and the whole expression will be interpreted as false
.
You can test it yourself in Playground.
c0 || c1 || c2
Symmetrically if you define an expression as the OR ||
concatenation of several clauses, then the whole expression is interpreted as true
(and the evaluation of the clauses does stop) as soon as the first true condition gets found.
Is there any expression in Swift that is similar to Python's for else syntax
You could just introduce a flag to record if break
is called or not. The statement
for a in b:
if c(a):
break
else:
d()
is the same as
found = False
for a in b:
if c(a):
found = True
break
if not found:
d()
But note that you don't need the for char in item.characters
loop at all, since you could just use the Set.isDisjointWith(_:)
method.
if cur_word.isDisjointWith(item.characters) {
maximum = ...
}
(On Swift 3 this method is renamed to Set.isDisjoint(with:)
)
Related Topics
How to Use Mingw's Gcc Compiler When Installing Python Package Using Pip
Pip Freeze Creates Some Weird Path Instead of the Package Version
How to Filter Lines on Load in Pandas Read_CSV Function
Pandas Extract Number from String
How to Rotate the Sprite and Shoot the Bullets Towards the Mouse Position
Scrape Multiple Pages with Beautifulsoup and Python
How to Highlight Searched Queries in Result Page of Django Template
Plotting of 2D Data:Heatmap with Different Colormaps
What Is Ruby Equivalent of Python's 'S= "Hello, %S. Where Is %S" % ("John","Mary")'
How to Decrypt Aws Ruby Client-Side Encryption in Python
In Python Can One Implement Mixin Behavior Without Using Inheritance
Get Protocol + Host Name from Url
Applying Udfs on Groupeddata in Pyspark (With Functioning Python Example)
How to Map Numeric Data into Categories/Bins in Pandas Dataframe
Make Executable File from Multiple Pyx Files Using Cython
In Django, How Does One Filter a Queryset with Dynamic Field Lookups