seq.forEach()
⛔ break : not allowed.
⛔ continue : not allowed.
❗ return : exit only from the current call to body. 👉 1️
// `seq.forEach(_:)` declaration:
func forEach(
_ body: (Self.Element) throws -> Void
) rethrows// sequence.forEach()
(1...10).forEach { n in
print(n)
// ⭐️ return from this closure, not from the `forEach` method
if n > 2 { return }
}
// 1, 2, ..., 10class ArticleGroupViewController: UIViewController {
private let articles: [Article]
override func viewDidLoad() {
super.viewDidLoad()
// ⭐️ 直接將 method 放入 forEach(),可增加程式的可讀性。
articles.forEach(addArticleView)
}
private func addArticleView(for article: Article) {
let articleView = ArticleView()
view.addSubview(articleView)
}
}Collections ⟩ Sequence ⟩ .forEach(_:)
Flow Control ⟩ for-in loop - iterate over a sequence (array, range, string, dictionary)
⟩ for...in ⭐️
forEach vs. for-in loop
Last updated
Was this helpful?