Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // FOR LOOPS
- // Over ranges
- let count = 1...10
- for number in count {
- print("Number is \(number)")
- }
- // Over arrays
- let beatles = ["John", "Paul", "George", "Ringo"]
- for beatle in beatles {
- print("\(beatle) was a member of the Beatles.")
- }
- // Use of underscore _
- for _ in 1...5 {
- print("Hi, five times")
- }
- // WHILE LOOPS
- var number = 1
- while number <= 20 {
- print(number) // Occurs 20 times
- number += 1
- }
- // REPEAT LOOPS
- number = 1
- repeat {
- print(number)
- number += 1
- } while number <= 20
- // EXITING LOOPS
- var countDown = 10
- while countDown >= 0 {
- print(countDown)
- if countDown == 4 {
- print("I'm bored. Let's go now!")
- break // Loop stops after "4"
- }
- countDown -= 1
- }
- // Exiting multiple loops
- outerLoop: for i in 1...10 { // Note: "outerloop" label
- for j in 1...10 {
- let product = i * j
- print ("\(i) * \(j) is \(product)")
- if product == 50 {
- print("It's a bullseye!")
- break outerLoop // break
- }
- }
- }
- // SKIPPING ITEMS IN LOOPS WITH "CONTINUE"
- for i in 1...10 {
- if i % 2 == 1 { // If number is odd, loop won't complete
- continue //
- }
- print(i)
- }
- // INFINITE LOOPS
- while true {
- // Some code
- // Make sure a condition exists to exit!
- }
Advertisement
Add Comment
Please, Sign In to add comment