ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်
Part 1 မှာ ဆောက်ထားတဲ့ TaskManager ကို ဒီ part မှာ core feature ဖြစ်တဲ့ task completion, filtering, sorting တွေ ထည့်ကြမယ်။ Closure ကို parameter အနေနဲ့ လက်ခံပြီး custom condition နဲ့ task list filter လုပ်တဲ့ method ရေးမယ်၊ ဒါက higher-order function pattern ကို practice လုပ်တာဖြစ်ပါတယ်။ Priority အလိုက် sort လုပ်ဖို့ sorted(by:) ကို custom comparator closure နဲ့ သုံးမယ်။ Pending task အရေအတွက်ကို get/set logic မလိုအောင် computed property အနေနဲ့ ရေးပြီး properties topic ကို reinforce လုပ်ပါလိမ့်မယ်။ ဒီအဆင့်ပြီးရင် app က data hold ရုံသက်သက်မက practical operation တွေ လုပ်နိုင်တဲ့ tool တစ်ခု ဖြစ်လာပါလိမ့်မယ်။
လက်တွေ့ ဆောက်ကြည့်မယ်
completeTask(id: Int) method ရေးပြီး matching id ရှိတဲ့ task ရဲ့ isDone ကို true ပြောင်းပါ (array index ကို firstIndex(where:) နဲ့ ရှာပါ)။ filter(by condition: (Task) -> Bool) -> [Task] method ရေးပြီး closure condition နဲ့ task array ကို filter ပြန်ပါ။ tasks(sortedBy:) method ရေးပြီး priority high->low order နဲ့ sorted array ကို return ပါ။ var pendingCount: Int computed property ကို ထည့်ပြီး isDone == false ဖြစ်တဲ့ task အရေအတွက်ကို return ပါ။ printAllTasks() ကို sortedBy priority order နဲ့ print ထုတ်အောင် update ပါ။
Code နမူနာ
extension TaskManager {
func completeTask(id: Int) {
if let index = tasks.firstIndex(where: { $0.id == id }) {
tasks[index].isDone = true
}
}
func filter(by condition: (Task) -> Bool) -> [Task] {
return tasks.filter(condition)
}
func tasksSortedByPriority() -> [Task] {
let order: [Priority] = [.high, .medium, .low]
return tasks.sorted {
order.firstIndex(of: $0.priority)! < order.firstIndex(of: $1.priority)!
}
}
var pendingCount: Int {
return tasks.filter { !$0.isDone }.count
}
}
manager.completeTask(id: 1)
let highPriorityTasks = manager.filter { $0.priority == .high }
print("High priority pending: \(highPriorityTasks.count)")
print("Total pending: \(manager.pendingCount)")completeTask ခေါ်ပြီးနောက် pendingCount က တစ်ခု လျော့သွားပြီး high priority filter result ကလည်း correct array ကို print ထုတ်ပါလိမ့်မယ်။၅ မိနစ် စမ်းကြည့်
isDone == true ဖြစ်တဲ့ task တွေချည်း filter ထုတ်တဲ့ line တစ်ကြောင်း ကိုယ်တိုင်ရေးကြည့်ပြီး completedCount ဆိုတဲ့ computed property တစ်ခု ထပ်ထည့်ကြည့်ပါ- 5 minute လောက် စမ်းကြည့်ပါ။
သတိလေးတစ်ချက်
Array element ကို struct value type ဖြစ်တဲ့အတွက် tasks[index].isDone = true လို index ကနေ တိုက်ရိုက် mutate ဖို့ လိုပါတယ်၊ for task in tasks loop ထဲက local copy ကို ပြောင်းလို့ original array မပြောင်းပါဘူး။