Thuta Learning
ရှာဖွေရန်
AdvancedProgrammingbeginner

Closures

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

Closure က variable ထဲသိမ်းနိုင်၊ function ထဲ parameter အနေနဲ့ပို့နိုင်၊ နောက်မှ run လုပ်နိုင်တဲ့ code block ပါ။ JavaScript က callback/lambda လိုမျိုးစဉ်းစားနိုင်ပါတယ်။ SwiftUI, async callback, sorting/filtering, button action တွေမှာ closures ကိုတွေ့ရပါမယ်။

swift
let names = ["Chris", "Alex", "Ewa", "Barry"]

let sortedNames = names.sorted { first, second in
    first < second
}

let shortNames = names.filter { name in
    name.count <= 4
}

print(sortedNames)
print(shortNames)

sorted ထဲက closure က item နှစ်ခုကို ဘယ်လိုနှိုင်းမလဲဆိုတာပြောပါတယ်။ filter ထဲက closure က item တစ်ခုကိုထားမလားဖယ်မလားဆုံးဖြတ်ပါတယ်။

You should see
["Alex", "Barry", "Chris", "Ewa"] ["Alex", "Ewa"]

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • Closure ထဲမှာ return type မရှင်းလင်းတဲ့ complex logic များလာရင် function သီးသန့်ခွဲရေးတာပိုဖတ်ရလွယ်ပါတယ်။
Closures | Thuta Learning