迴圈控制 Loop Statement


標籤

for 迴圈

  • 基本架構
    for (值) in (陣列) {
        (執行的動作)
    }
    
  • 數字
    for i in 1...5 {
        print("\(i) ", terminator: "")
    }
    
    • 輸出結果
      1 2 3 4 5
      
  • 陣列
    for i in ["a", "b", "c", "d"] {
        print("\(i) ", terminator: "")
    }
    
    • 輸出結果
      a b c d
      
  • 字典
    let dictionary = [1: "John", 2: "Harry", 3: "Kevin", 4: "Alex"]
    for(i, j) in dictionary {
        print("\(i): \(j) ", terminator: "")
    }
    
    • 輸出結果
      2: Harry 3: Kevin 1: John 4: Alex
      
  • 純循環(不取值 )
    for _ in 1...5 {
        print("GOOD ", terminator: "")
    }
    
    • 輸出結果
      GOOD GOOD GOOD GOOD GOOD
      
  • 純循環(加入運算子 )
    var data = 0, data2 = 50
    for _ in 1...5 {
        data += data2
    } 
    print(data)
    
    • 輸出結果
      250
      
  • 隨機取值
    var number: UInt32
    for _ in 1...5 {
        number = arc4random_uniform(100)
        print("\(number) ", terminator: "")
    }
    
    • 輸出結果
      47 40 25 6 53
      
      • 附註:number 取值需放於迴圈中才能執行五次動作,否則如下。
        65 65 65 65 65
        

while 迴圈

  • 基本架構
    while (條件) {
        (條件滿足,執行的動作)
    }
    
    var data = 0, data2 = 50
    while data == 0 {
        data = data2
    } 
    print(data)
    
    • 輸出結果
      50
      
  • 運算(從50 加回0 )
    var data = 0, data2 = 50
    while data2 >= 0 {
        data += data2
        data2 -= 1
    }
    print(data)
    
    • 輸出結果
      1275
      
      • 附註:data2 的位子決定結果是 50 +...+ 0,或是 49 +...+ 2。
  • repeat while
    repeat {
        (條件滿足,執行的動作)
    } while (條件)
    
    var data = 0, data2 = 50
    repeat {
        data = data2
    } while data == 0
    print(data)
    
    • 輸出結果
      50
      

巢狀迴圈

  • for 迴圈 & for 迴圈
    for i in 1...5 {
        print("\(i) ", terminator: "")
        for j in 1...5 {
            print("\(j)", terminator: "")
        }
        print("")
    }
    
    • 輸出結果
      1 12345
      2 12345
      3 12345
      4 12345
      5 12345
      
  • for 迴圈 & while 迴圈
    for i in 1...5 {
        var j: Int = 0
        while j <= i {
            print("\(j)", terminator: "")
            j += 1
        }
        print("")
    }
    
    • 輸出結果
      01
      012
      0123
      01234
      012345
      
  • 巢狀迴圈 & 運算子
    for i in 1...3 {
        for j in 1...3 {
            print("\(i) + \(j) = \(i + j) ", terminator: "")
        }
        print("")
    }
    
    • 輸出結果
      0 + 0 = 0 0 + 1 = 1 0 + 2 = 2 0 + 3 = 3
      1 + 0 = 1 1 + 1 = 2 1 + 2 = 3 1 + 3 = 4
      2 + 0 = 2 2 + 1 = 3 2 + 2 = 4 2 + 3 = 5
      3 + 0 = 3 3 + 1 = 4 3 + 2 = 5 3 + 3 = 6
      

results matching ""

    No results matching ""