Logical branches and cyclic bodies of Swift study Notes
- 2020-06-07 05:23:40
- OfStack
Introduction to Branches
The branch is the judgment statement such as if/switch/3 mesh operator The execution flow of the program can be controlled through branch statements1.if
OC
if(a>0)NSlog(@"yes");
Swift
if else is used in the same way as OC1, except that there are no parentheses after the conditional statement. 3. Order operator and OC base 1;
2.guard
guard is a new syntax for swift2.0
Much like the if statement, it is designed to improve the readability of the program
The guard statement must be accompanied by an else statement, with the following syntax
When the conditional expression is true, the content in the else statement is skipped and the statement group content is executed
When the conditional expression is false, execute else statement content, is return jump statements 1, break, continue, throw
// if 1 Six adults can only surf the Internet with their province id CARDS
func cherk(age:Int hasCard:Bool){
if age >= 18{
if hasCard{
print(" The boss , A machine ")
}else{
print(" Get your ID card at home ")
}
else{
print(" Minors cannot access the Internet ")
}
}
func cherkGuard(age:Int hasCard:Bool){
guard age >= 18 else {
print(" The boss , A machine ")
return
}
guard hasCard else {
print(" Go home and get your province card ")
return
}
print(" Minors cannot access the Internet ")
}
2. Basic use of switch
In the OC
In the Swift
3. Special use of switch
Range match
Interval concept:
This is usually described as a numeric interval
Half open half closed interval
Closed interval
let range = 0...10// The closed interval represents the interval 0~10
let range1 = 0..<10 A half-open and half-closed interval represents an interval 0~9
Interval operation:
A tuple matching
let point = (10,15)
switch point{
case (0,0)
print(" Coordinates at the origin ")
case (1...10,1...10)// An interval may be added to the primitive
print(" coordinates X,Y in 1...10 between ")
case (,0)// An interval may be added to the primitive
print(" coordinates X in X On the shaft ")
default
print(" other ")
}
Value binding
let point = (10,15)
switch point{
case (var x,0)
print("x=\(x)")//point In the x Assigned to x
case (10,var y)
print("y=\(y)")//point In the y Assigned to y
case var(x,y)
print("x=\(x) y=\(y)")//point In the xy Assigned to xy
default
print(" other ")
}
Conditional binding
let point = (100,10)
switch point{
// only where The following conditional statement expression assigns a value to a property and executes it case The following statement
case var( x,y) where x > y
print("x=\(x) y=\(y)")
default
print(" other ")
}
3. for cycle
Range of writing
for _ in 0..<10{ //_ Is for neglect
print("xxx")
}
4.while cycle and do while cycle
while cycle
var i =10
while i > 0{
i-=1;
print (i)
}
do while cycle
repeat {//swift Not in the do ,do in swift Have special meaning , Used to catch exceptions
i +=1
print(i)
}while i < 10
conclusion