🖥️
iOS App with Pop
UIKit Swift 5
UIKit Swift 5
  • iOS App development
  • Swift
    • Variable & Constant
    • Number & String
    • Operator
    • Array, Dictionary & Tuple
    • Enum
    • Optional
    • Function
    • Class & Struct
    • Branching
    • Loops
    • Error handler
    • Protocol
    • Extension
  • Create New Project
  • Introduction to Xcode
  • Scene-Based Life-Cycle
  • UIViewController
  • Storyboard
  • First Run
  • Display todo list
  • Basic Auto Layout
  • MVC
  • Model
  • Binding TableView
  • Binding TableViewCell
  • TableViewDelegate
  • Add navigationBar with + button
  • Add new item page
  • TextField and Switch
  • Binding action
  • Add mock item to todo list
  • What is weak?
  • Finish add item
  • Delete todo item
  • Edit todo item
  • Custom new layout
  • Adding new delegate
  • Refactor
  • Pushing edit view
  • Large navigation
  • Drag item
  • Drop item (in app)
  • Save data
  • Where to go from here?
Powered by GitBook
On this page
  1. Swift

Loops

การวนลูปคือการรันคำสั่งในบล๊อกของลูปซ้ำหลาย ๆ ครั้งตามจำนวนหรือเงื่อนไขที่กำหนด เช่น วนพิมพ์ค่าตั้งแต่ 0 ถึง 9

โดยทั่วไปหลาย ๆ ภาษาจะสามารถเขียนลูปได้แบบนี้

for(int i = 0; i < 10; i++)
   printf("i=%d\n", i);

แต่ใน Swift จะไม่สามารถเขียนแบบนี้ได้ แต่ให้เขียนเป็นลูป for in แทน เราสามารถใช้ range มาช่วยได้แบบนี้

for i in 0..<10 {
    print(i)
}

ในบางครั้งเราต้องการเพิ่มค่า i ทีละ 2 แบบนี้

for(int i = 0; i < 10; i += 2)

Swift จึงเตรียมฟังก์ชั่น stride(from:to:by:) ให้แบบนี้

for index in stride(from: 0, to: 10, by: 2)
// index is 0, 2, 4, 6, 8

หรือ stride(from:through:by:) ให้แบบนี้

for index in stride(from: 0, through: 10, by: 2)
// index is 0, 2, 4, 6, 8, 10

เราสามารถวนแบบ for each ได้ด้วยการเขียน for in แบบเดียวกัน เช่น

var shoppingList = ["catfish", "water", "tulips"]
for item in shoppingList {
    print(item)
}

ในกรณีที่เราต้องการ index ของ item ที่วนลูปอยู่ด้วย ให้เราใช้ tuple มารับผลลัพธ์จาก enumerated() อีกทีนึง

for (index, item) in shoppingList.enumerated() {
    print("The item at index \(index) is \(item)")
}

เราสามารถใส่เงื่อนไขการเข้าทำงานในลูปได้ด้วย where ทำให้ลดการใส่ if ในลูปของเราได้ด้วย

for item in shoppingList where item.starts(with: "c") {
    print(item)
}

ทั้งยังสามารถใช้ break ในการหยุดและออกจากลูปทันที หรือใช้ continue ในการข้ามไปยังลูปครั้งถัดไปได้เหมือนภาษาอื่น

นอกจาก for ยังมี while กับ repeat while ด้วย

ในกรณีที่ต้องการเช็คเงื่อนไขก่อนให้ใช้ while

while shoppingList.count > 0 {
    print(shoppingList.remove(at: 0))
}

ในกรณีที่ต้องการทำคำสั่งในบล๊อกก่อนหนึ่งรอบแล้วค่อยเช็คเงื่อนไขใช้ repeat while

repeat {
    print(shoppingList.remove(at: 0))
} while shoppingList.count > 0
PreviousBranchingNextError handler

Last updated 2 years ago