GregLeck

Loops2

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