Swift Dynamic Variable Name depend on value

后端 未结 2 1777
心在旅途
心在旅途 2021-01-23 07:29

I had a list of variable name like this (BankHelper.swift):

static var va_1_atm =
\"\"\"
  1. Silahkan kunjungi ATM terdekat
2条回答
  •  爱一瞬间的悲伤
    2021-01-23 07:59

    Solution with Array

    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 = "die sad" 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
    

    Solution with Dictionary

    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 = "die sad" 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
    

    Solution with Mirror

    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 = "die sad" 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
    

    Solution with NSObject

    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 = "die sad" 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
    

提交回复
热议问题