๐for...in
Swift โฉ flow control โฉ loop โฉ for...in
๐ replit
var a1 = [Int]()
var a2 = [Int]()
var a3 = [Int]()
var a4 = [Int]()
var a5 = [Int]()
/*
for-in loop
-----------
- โ
continue: skip to next element
- โ
break : break the loop completely
- โ return : invalid outside of a function
*/
// 'break' in for-in loop
for n in 1...10 {
if n > 3 { break } // โญ break for-loop completely
a1.append(n)
}
// โญ [1, 2, 3]
print(a1)
/*
.forEach()
-----------
- โ continue: not allowed
- โ break : not allowed
- โ return : return from closure only
*/
// early 'return' in forEach
(1...10).forEach { n in
if n > 2 { return } // โญ early return
a2.append(n) // โญ number NOT appended
}
// โญ [1, 2]
// late 'return' in forEach
(1...10).forEach { n in
a3.append(n) // โญ number appended
if n > 2 { return } // โญ late return from closure
}
// โญ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// โ 'continue' in forEach not allowed
(1...10).forEach { n in
// โ error: 'continue' is only allowed inside a loop
if n > 2 { continue }
a4.append(n)
}
// โ 'break' in forEach not allowed
(1...10).forEach { n in
// โ error:
// - unlabeled 'break' is only allowed inside a loop or switch
// - labeled 'break' is required to exit an `if` or `do`
if n > 2 { break }
a5.append(n)
}
// for ... in ... where ...
for article in articles where !article.isDraft { // โญ๏ธ where clause
results.append(article)
guard results.count < 5 else { break } // โญ๏ธ break for-loop entirely
}
Collections โฉ Sequence โฉ .forEach(_:)
Flow Control โฉ for-in loop - iterate over a sequence (array, range, string, dictionary)
seq.forEach() โญ๏ธ
Last updated