Control Flow
If and switch are used as condition statements, and for-in, for, while, and do-while are used as loops. Conditions and loop parentheses can be left blank, however, parentheses outside the body must be written.
1 let individualScores = [75,43,103,87,12]2 var teamScore = 03 for score in individualScores{4 if score > 50{5 temScore +=36 } else {7 tempScore +=18 }9 }
teamScore
In the if statement, the condition must be a boolean expression, which means that if the code is if socret {...}, it is incorrect and cannot be implicitly compared with 0.
You can use if and let to lock the value of a variable, and add a question mark after the declared type of the variable? Marking this variable is optional
var optionalString: String?="Hello"optionalString == nil var optionaLName: String?="John Appleseed"var greeting = "hello!"if let name = optionlName { greeting = "Hello, \(name)"}
Set optionalName to nil to see what the result is?
If the optional value is nil, the condition is false and the code node is skipped. In other cases, after the optional value is assigned to the let constant, this allows the code in the if structure to be executed
The switch supports all types of data and various operations. They are not limited to the integer type and the detection is equal, as shown below:
let vegetable = "red pepper"switch vegetable { case "celery": let vegetableComment = "add some raisins and make ants on a log." case "cucumber","watercress": let vegetableComment ="That would make a good tea sandwich." case let x where x.hasSuffix("pepper"): let vegetableComment ="Is it a spicy \(x)?" default: let vegetableComment = "Everything tastes good in soup." }
After the code in the structure block with matching conditions is executed, the program will exit the switch statement and will not execute the next case
You can use the for-in statement to traverse the items in the dictionary and provide them with a key value:
let interestingNumbers = [ "Prime":[2,3,5,7,11,13] "Fibonacci": [1,1,2,3,5,8] "Square": [1,4,9,16,25]]var largest = 0for (kind, numbers) in interestingNumbers{ for number in numbers{ if(number > largest) { largest = number } }}
largest
The while clause is used to loop the code block until the condition changes. The condition of a loop can be replaced at the end, so that the execution is performed once less:
var n = 2while n < 100{ n = n*2}nvar m = 2do { m = m*2}while m <100m
You can also use... to create a range set, and write an Explicit initialization index, condition, and increment to judge. The following two are:
var firstForLoop = 0for i in 0..3{ firstForLoop += i}firstForLoopvar secondForLoop = 0for var i = 0; i<3; i++{ secondForLoop += i}secondForLoop
Use... to make a range