This is the sixth day of my participation in Gwen Challenge

Conditional statement (If statement,A switch statement)

If statement

  • ifSingle branched structure
let temperature = 28
if temperature <= 25 {
    print("Low temperature")}Copy the code
  • ifDouble sub selection support structure
let temperature = 28
if temperature <= 25 {
    print("Low temperature")}else if temperature >= 30 {
    print("High temperature")}Copy the code
  • ifMulti – branch selection structure
let temperature = 28
if temperature <= 25 {
    print("Low temperature")}else if temperature >= 30 {
    print("High temperature")}else {
    print("The temperature is just right.")}Copy the code

A switch statement

Switch statements can be considered when there are usually more than three branches to determine the condition, and continuing with if-else code seems long and logical

let phoneType = "apple"

switch phoneType {
case "huawei":
    print("Huawei")
case "apple":
    print(The word "apple")
case "xiaomi":
    print("Millet")
default:
    print("Other Phones")}Copy the code
  • In Swift, there is no need to use the break statement explicitly

    In OC, if a break is not written in the case of the switch, each case below the match will be executed, whereas in Swift, the switch statement will be terminated as soon as the first match is found, without proceeding to the next case branch

let phoneType = "apple"

switch phoneType {
case "huawei":
    print("Huawei")
case "apple":
    print(The word "apple")
case "xiaomi":
    print("Millet")
default:
    print("Other Phones")}logApple:Copy the code
  • When multiple conditions can be treated in the same way, you can group the possibilities togethercaseAfter, and separated by a comma
let phoneType = "xiaomi"

switch phoneType {
case "huawei"."xiaomi"."oppo":
    print("China Mobile")
case "apple"."google":
    print(American Cell phone)
case "samsung":
    print("Korean Mobile phone")
default:
    print("Other Phones")}log: Chinese mobile phoneCopy the code
  • switchThe statement can check whether the value it determines is contained in acaseWithin the scope of.
let value = 25
switch value {
case 10:
    print("value = 10")
case 20 ..< 40:
    print("20 < value < 40")
case 50:
    print("value = 50")
default:
    print(value)
}

log
20 < value < 40
Copy the code
  • switchStatement can determine the value of a tuple. The elements in a tuple can be values or ranges. Also, use underscores (_) to match all values
let somePoint = (1.1)
switch somePoint {
case (0.0):
    print("\ [somePoint) origin")
case (_, 0):
    print("\(somePoint) on the x axis")
case (0, _):
    print("\(somePoint) on y axis")
case (-2..2., -2..2.):
    print("\(somePoint) in the zone")
default:
    print("\(somePoint) outside the area")}log:
(1.1) In the zoneCopy the code
  • caseBranching allows matching values to be declared as temporary constants or variables, and incaseThe clade is used in vivo, and this behavior is calledValue binding
let anotherPoint = (0.2)
switch anotherPoint {
case (let x, 0):
    print("The X-axis value is \(x)")
case (0.let y):
    print("The value of the Y-axis is \(y)")
case let (x, y):
    print("The coordinates of the point are (\(x), \(y))")}logThe Y-axis value is2
Copy the code
  • You can usewhereStatement to determine additional conditions
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
    print("(\(x), \(y)) on x == y line")
case let (x, y) where x == -y:
    print("(\(x), \(y)) on x == -y line")
case let (x, y):
    print("(\(x), \(y)) is just any point")}log:
(1, -1) on the x == -y lineCopy the code

Loop statement (for-in,while,repeat-While)

The for in statement

  • for-inLoop over array
let arr = ["A"."B"."C"]
for str in arr {
    print(str);
}

log:
A
B
C
Copy the code
  • for-inLooping dictionary
let dic = ["keyA":"a"."keyB":"b"]
for (key,value) in dic {
    print("\(key)---\(value)"} log: keyA-- a keyB-- bCopy the code
  • for-inThe loop iterates over a range of values
for index in 1 ..< 3{print(index)} log:1
2
Copy the code
  • If you don’t need every value in the range, you can use underscores (_Ignore these values instead of variable names
var a = 2
let b = 3
for _ in 1. b { a += b } print(a)log:11
Copy the code
  • Unneeded printed values can be skipped
    • The stride(from:to:by:) is an open range

      for value in stride(from: 0, to: 10, by: 2) {
          print(value)
      }
      
      log:
      0    2   4   6   8
      Copy the code
    • Stride (from:through:by:) The closed range is a closed range

      for value in stride(from: 0, through: 10, by: 2) {
          print(value)
      }
          
      log:
      0    2   4   6   8    10
      Copy the code

While statement

  • The while loop

    Each time the conditional expression is evaluated at the start of the loop, the body of the loop is executed if the expression value is true. After executing the body of the loop, the conditional expression is evaluated, and the loop is not terminated until the condition is false

var a = 3
while a > 0 {
    a -= 1
    print(a)  / / 2, 1 0} the log:2
1
0
Copy the code
  • Repeat – the while loop

    A variant of the repeat-while loop, similar to the do-while in other languages, executes the loop once, evaluates the loop condition expression, and repeats until the expression is false before the loop terminates

var a = 0
repeat {
    a += 1
    print(a)  
} while a < 3

log:
1 
2 
3
Copy the code

Control steering statement (continue,break,fallthrough,return,throw)

Continue: Terminates this loop and restarts the next loop

for i in 0 ..< 5 {
    if i == 2 {
        continue
    }
    print("i = \(i)")}log:
i = 0
i = 1
i = 3
i = 4
Copy the code

Break: Terminates the execution of the entire loop

for i in 0 ..< 5 {
    if i == 2 {
        break
    }
    print("i = \(i)")}log:
i = 0
i = 1
Copy the code

fallthrough

Since the switch in Swift executes as soon as the first matched case branch completes its execution, the entire switch block completes its execution without requiring the insert break statement that you display, whereas the OC statement may execute the following case branches without inserting a break statement: If you need to implement the same features as OC, you can use fallthrough statements here

let flag = 5
var description = "Beijing"
switch flag {
case 5:
    description += "The"
    fallthrough
case 10:
    description += "Winter"
default:
    description += "It's all haze"} print(description) log Beijing winterCopy the code

Return and throw jump out of scope

func showValue() {
    for i in 0 ..< 5 {
        print("i = \(i)")
        if i == 2 {
            return
        }
    }
}
print(showValue())

log:
i = 0
i = 1
i = 2
Copy the code

guard… else

  • Be able to useif... elseCan be used anywhereguard... elseBut not the other way around.guardBe sure to andelseThey must be used together, and they must be used in functions
  • The statement group is executed when the conditions for the statement are met, but when they are not, the statement group is executedelse, and must be writtenbreak,return,continue,throwAnd other keywords as the terminator
class Student: NSObject {
    func showScore(score:Int) {
        guard score >= 60 else {
            print("Fail the exam")
            return
        }
        print(score)
    }
}
let student = Student()
student.showScore(score: 50)

logI failed the examCopy the code

Check API availability

  • Swift supports checking API availability, which ensures that we don’t accidentally use an unavailable API on our current deployment machine
if #available(iOS 10, macOS 10.12, *) {
    Use iOS 10 APIs on iOS, and Use macOS 10.12 APIs on macOS
} else {
    // Fall back to earlier iOS and macOS APIs
}
Copy the code