Swift: 用变量调用元组成员?

Swift: call tuple member with variable?

基本问题。如果我有以下内容:

let unitPrice = (fighter: 15, cleric: 20, mage: 25)
var unitType = "cleric"

如何调用unitPrice.unitType

所以它等于 unitPrice.cleric (20)?

听起来您真正要找的是字典,而不是元组。 请尝试以下操作:

// Using an enum instead of a String ensures there are no errors from spelling mistakes.
enum UnitType {
    case Fighter
    case Cleric
    case Mage
}

let unitPrice: [UnitType : Int] = [.Fighter : 15, .Cleric : 20, .Mage : 25]

// Retrieving the price of a Cleric...
let type = UnitType.Cleric
if let price = unitPrice[type] {
    print(price) // 20
}