GregLeck

Loops

Sep 26th, 2019
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.35 KB | None | 0 0
  1. import UIKit
  2.  
  3. // FOR LOOPS
  4.  
  5. // Over ranges
  6. let count = 1...10
  7. for number in count {
  8.     print("Number is \(number)")
  9. }
  10.  
  11. // Over arrays
  12. let beatles = ["John", "Paul", "George", "Ringo"]
  13. for beatle in beatles {
  14.     print("\(beatle) was a member of the Beatles.")
  15. }
  16.  
  17. // Use of underscore _
  18. for _ in 1...5 {
  19.     print("Hi, five times")
  20. }
  21.  
  22. // WHILE LOOPS
  23. var number = 1
  24. while number <= 20 {
  25.     print(number) // Occurs 20 times
  26.     number += 1
  27. }
  28.  
  29. // REPEAT LOOPS
  30. number = 1
  31. repeat {
  32.     print(number)
  33.     number += 1
  34. } while number <= 20
  35.  
  36.  
  37. // EXITING LOOPS
  38. var countDown = 10
  39. while countDown >= 0 {
  40.     print(countDown)
  41.     if countDown == 4 {
  42.         print("I'm bored. Let's go now!")
  43.         break  // Loop stops after "4"
  44.     }
  45.     countDown -= 1
  46. }
  47.  
  48. // Exiting multiple loops
  49. outerLoop: for i in 1...10 {  // Note: "outerloop" label
  50.     for j in 1...10 {
  51.         let product = i * j
  52.         print ("\(i) * \(j) is \(product)")
  53.  
  54.         if product == 50 {
  55.             print("It's a bullseye!")
  56.             break outerLoop     // break
  57.         }
  58.     }
  59. }
  60.  
  61. // SKIPPING ITEMS IN LOOPS WITH "CONTINUE"
  62. for i in 1...10 {
  63.     if i % 2 == 1 { // If number is odd, loop won't complete
  64.         continue    //
  65.     }
  66.     print(i)
  67. }
  68.  
  69. // INFINITE LOOPS
  70. while true {
  71.     // Some code
  72.     // Make sure a condition exists to exit!
  73. }
Advertisement
Add Comment
Please, Sign In to add comment