Swift Process Control
//: Playground-noun: a place where people can play
Import UIKit
// Use if and switch as conditions. Use for-in, for, while, and do-while as loops. Parentheses are not mandatory, but the braces of the main body are required.
Let individualScores = [75, 43,103, 87, 12]
Var teamScore = 0
For score in individualScores {
If score> 50 {
TeamScore + = 3
} Else {
TeamScore + = 1
}
}
TeamScore
/* In the if statement, the condition must be a Boolean expression, which means that if score {...} is incorrect and cannot be implicitly compared with 0. You can use if and let together to prevent value loss. These values are optional. Optional values can contain a value or an nil to specify
Does not exist. Write a question mark? After the type, the value is optional. */
Var optionalString: String? = Hello
OptionalString = nil
Var optionalName: String? = John Appleseed
Var greeting = Hello
If let name = optionalName {
Greeting = Hello, (name)
} Else {
Greeting = Word
}
// If the optional value is nil, the condition is false,
// The switch supports multiple types of data and multiple comparisons, and must not be an integer.
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 wocould make a goog tea sandwich.
Case let x where x. hasSuffix (pepper ):
Let vegetableComment = Is it a spicy (x )?
Default:
Let vegetableComment = Everything tastes goog in soup.
}
// You can use for-in to iterate each element in the dictionary and provide a pair of names to use each key-value pair.
Let interestingNumbers = [
Prime: [2, 3, 5, 7, 11, 13],
Fibonacci: [1, 1, 2, 3, 90, 8],
Square: [1, 4, 9, 16, 25],
]
Var largest = 0
Var str: String?
For (kind, numbers) in interestingNumbers {
For number in numbers {
If number> largest {
Largest = number
Str = kind
}
}
}
Largest
Str
// Use while to repeatedly execute the code block until the condition changes. Loop conditions can be placed at the end to ensure that the loop is executed at least once.
Var n = 2
While n< 100 {
N = n * 2
}
N
Var m = 2
Do {
M = m * 2
} While m <100
M
// You can keep an index in the loop. You can use the... to indicate the index range or explicitly declare an initial value, condition, or increment. These two loops do the same thing:
Var firstForLoop = 0
For I in 0 .. <3 {
FirstForLoop + = I
}
FirstForLoop
Var secondForLoop = 0
For var I = 0; I <3; I ++ {
SecondForLoop + = 1
}
SecondForLoop
// The maximum value is ignored by using the... <construction range, while the range constructed by the... contains two values.
Var num1 = 0
Var num2 = 0
For I in 1 .. <4 {
Num1 ++
}
Num1
For I in 1... 4 {
Num2 ++
}
Num2