1.for loop
for index in 1...5 // Here index is constant and value set with each iteration
{
print("\(index) times 5 is \(index * 5)")
}
for _ in 1…10
{
print(“print”)
}
2.while loop
while condition
{
statements
}
repeat //like do while
{
statements
} while condition
3.if and if-else
var temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
}
else {
print("It's not that cold. Wear a t-shirt.")
}
4.switch :
break keyword not required. support more data type. multiple switch
cases can have same value but first matching is executed. each case have atleast
one statement otherwise its error(use break for empty cases).
switch some value to consider {
case value 1:
respond to value 1
case value 2, value 3:
respond to value 2 or 3
case half open or closed range: // 1..<5 10…1000
respond to range
case tuple //tuple can contain wildcard character. ( _ ,0 ) means first element can be
anything.
respond to tuple
default:
otherwise, do something else
}
half open or closed range returns either intervaltype or a range.
Value binding in switch where clause in switch to check for additional conditions.
switch case can bind/assign the value to temp const/value.
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0): // first value can be anything second should be 0
print("on the x-axis with an x value of \(x)")
case (0, let y):
print("on the y-axis with a y value of \(y)")
case let (x, y) where x==y:
print("somewhere else at (\(x), \(y))")
case let (x, y) where x== (-y):
print("somewhere else at (\(x), \(y))")
case let (x, y):
print("somewhere else at (\(x), \(y))")
}
Control transfer protocol:
continue , break , return , fallthrough, throw.
continue : skip current iteration
break: ends execution of loop
fallthrough: behavior like c in switch if not break then go to next case use .fallthrough as swift break behavior is default.
return: get out of function
throw: to raise exception
Labeled Statement
like c , used to break or continue.
label name: while condition
{
statements
}
guard: guard statement is like if statement , executes statement based on boolean value of expression.
guard let location = person["location"] else {
print("I hope the weather is nice near you.")
return
}
You can think of guard more like an Assert, but rather than crashing, you can
gracefully exit. with guard fail case else clause must transfer control to exit the code block in
which the guard statement appears.
guard is used mostly better readability than if.
Checking API Availability
if #available(iOS 9, OSX 10.10, *) { //*, is required and specifies that on any other platform any other platform . min os version
// Use iOS 9 APIs on iOS, and use OS X v10.10 APIs on OS X
} else {
// Fall back to earlier iOS and OS X APIs
}
0 comments:
Post a Comment