不确定我是否正确地问了这个问题。但基本上我想通过字符串值和/或枚举来引用类的成员
例如,我有以下内容。
var total:Int = 0
if locale.currencyCode == "JPY" {
for item in Cart.items {
total += item.fabric.price.JPY * item.quantity
}
}else{
for item in Cart.items {
total += item.fabric.price.USD * item.quantity
}
}
subtotalAmountLabel.text = "\(total.formatMoney())"
但是,我想写类似下面的内容。
var total:Int = 0
for item in Cart.items {
total += item.fabric.price[locale.currencyCode]* item.quantity
}
subtotalAmountLabel.text = "\(total.formatMoney())"
有没有办法做到这一点?
答案 0 :(得分:1)
您应该改用字典。
// this should be the declaration of item.fabric.price
let prices = [
"JPY": <some price>,
"USD": <some price>,
// and so on
]
然后您可以使用字符串来访问它:
if let price = item.fabric.prices[locale.currencyCode] {
// ...
} else {
// If execution ever reaches here, that means there is no price available in that currency.
}