Swift basic control flow

Swift provides a flow control structure similar to C language, including for and while loops that can execute tasks multiple times, if and switch statements that select to execute different code branches based on specific conditions, and break and continue that control the flow to jump to other codes Statement.

In addition to the traditional for conditional increment loop in C, Swift also adds a for-in loop to traverse arrays, dictionaries, ranges, strings and other sequence types more easily.

Swift's switch statement is more powerful than C language. In C language, if a case accidentally misses break, this case will "fall into" the next case. Swift does not need to write break, so this "fall into" situation will not happen. Case can also match more type patterns, including range matching, tuples and descriptions of specific types. The matched value in a switch case statement can be determined by a temporary constant or variable inside the case body, or a where clause can describe more complex matching conditions.

1. if statement

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    
    
    if score > 50 {
    
    
        teamScore += 3
    } else {
    
    
        teamScore += 1
    }
}
print(teamScore)

In the if statement, the condition must be a boolean expression-code like if score {…} is wrong.

2. Use if and let to handle missing values

You can use if and let together to handle missing values. The value of some variables is optional. An optional value may be a specific value or nil, indicating that the value is missing. Add a question mark after the type to mark that the value of this variable is optional.

var optionalString: String? = "Hello"
optionalString == nil

var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    
    
    greeting = "Hello, \(name)"
}
print(greeting)

Exercise : Change optionalName to nil. What will greeting be? Add an else statement to assign a different value to greeting when optionalName is nil.

If the optional value of the variable is nil, the condition will be judged to be false, and the code in braces will be skipped. If it is not nil, the value will be assigned to the constant after let so that the value can be used in the code block.

3. The switch statement

Switch supports any type of data and various comparison operations-not just integers and testing for equality.

let vegetable = "red pepper"
switch vegetable {
    
    
case "celery":
    let vegetableComment = "Add some raisins and make ants on a log."
    print(vegetableComment)
case "cucumber", "watercress":
    let vegetableComment = "That would make a good tea sandwich."
    print(vegetableComment)
case let x where x.hasSuffix("pepper"):
    let vegetableComment = "Is it a spicy \(x)?"
    print(vegetableComment)
default:
    let vegetableComment = "Everything tastes good in soup."
    print(vegetableComment)
}

Exercise : Delete the default statement and see what errors will occur?

After running the matched clauses in the switch, the program will exit the switch statement and will not continue to run down, so there is no need to write break at the end of each clause.

4. For-in statement

You can use for-in to traverse the dictionary, and you need two variables to represent each key-value pair.

let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25]
]
var largest = 0
for (kind, numbers) in interestingNumbers {
    
    
    print(kind)
    for number in numbers {
    
    
        largest = number
        print(largest)
    }
}

Exercise : Add another variable to record which type of number is the largest.

You can use... in the loop to indicate the range, or you can use the traditional way of writing, the two are equivalent:

// for-in 循环范围
var firstForLoop = 0
for i in 0...3 {
    firstForLoop += i
}
print(firstForLoop)

5. While statement

Use while to repeatedly run a piece of code until the condition is not met. The loop condition can be at the beginning or at the end.

var n = 2
var number = 0

while n < 100 {
    
    
    number += 1
    n = n * 2
}
print(n,number)

var m = 2
repeat {
    
    
    m = m * 2
} while m < 100
print(m)

Welcome to follow the official account [Swift Community]:

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_36478920/article/details/103425455