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

Properties

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

Properties တွေက struct/class/enum ထဲမှာ data သိမ်းတဲ့ variable/constant တွေပါ။ Stored property က data ကိုတကယ်သိမ်းတယ်။ Computed property ကတော့ တခြား data တွေပေါ်မူတည်ပြီး တန်ဖိုးကိုတွက်ပြန်ပေးပါတယ်။

swift
struct Product {
    var name: String
    var price: Double
    var discountPercent: Double

    var finalPrice: Double {
        price - (price * discountPercent / 100)
    }
}

let plan = Product(name: "Pro Plan", price: 20.0, discountPercent: 10)
print("\(plan.name): $\(plan.finalPrice)")

name, price, discountPercent တွေက stored properties ပါ။ finalPrice က computed property ဖြစ်ပြီး discount တွက်ပြီးမှ result ပြန်ပေးပါတယ်။

You should see
Pro Plan: $18.0

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

  • Computed property ထဲမှာ သူ့ကိုယ်သူပြန်ခေါ်တဲ့ logic ရေးမိရင် infinite recursion ဖြစ်နိုင်ပါတယ်။
Properties | Thuta Learning