I had a list of variable name like this (BankHelper.swift):
static var va_1_atm =
\"\"\"
- Silahkan kunjungi ATM terdekat
With continuous integer values, you can make them indexes of an Array
.
class BankHelper {
static var va_1_atm = "les gorilles"
static var va_2_atm = "in comedy"
static var va_3_atm = ""
fileprivate static var all = [va_1_atm, va_2_atm, va_3_atm]
static func string(for bankAccount: Int) -> String? {
return all[bankAccount - 1]
}
}
Usage:
cell.bankDesc.text = BankHelper.string(for: ReservationModel.bankAccount)!.htmlToString
With discontinuous values, you can make them keys of a Dictionary
.
class BankHelper {
static var va_1_atm = "les gorilles"
static var va_2_atm = "in comedy"
static var va_3_atm = ""
fileprivate static var all = [1: va_1_atm, 2: va_2_atm, 3: va_3_atm]
static func string(for bankAccount: Int) -> String? {
return all[bankAccount]
}
}
Usage:
cell.bankDesc.text = BankHelper.string(for: ReservationModel.bankAccount)!.htmlToString
Alternatively, you may use mirroring to retrieve an instance variable by name (which means that your variables can't be static
for this to work), but you may consider a singleton pattern.
class BankHelper {
var va_1_atm = "les gorilles"
var va_2_atm = "in comedy"
var va_3_atm = ""
func string(for bankAccount: Int) -> String? {
return Mirror(reflecting: self).descendant("va_\(bankAccount)_atm") as? String
}
}
Usage:
cell.bankDesc.text = BankHelper().string(for: ReservationModel.bankAccount)!.htmlToString
You need arbitrary access to static variables? Use a layer of Objective-C by conforming to NSObject
.
class BankHelper: NSObject {
@objc static var va_1_atm = "les gorilles"
@objc static var va_2_atm = "in comedy"
@objc static var va_3_atm = ""
static func string(for bankAccount: Int) -> String? {
return value(forKey: "va_\(bankAccount)_atm") as? String
}
}
Usage:
cell.bankDesc.text = BankHelper.string(for: ReservationModel.bankAccount)!.htmlToString