Variables Swift:用变量调用元组成员?
基本问题。如果我有以下资料:Variables Swift:用变量调用元组成员?,variables,swift2,tuples,member,Variables,Swift2,Tuples,Member,基本问题。如果我有以下资料: let unitPrice = (fighter: 15, cleric: 20, mage: 25) var unitType = "cleric" // Using an enum instead of a String ensures there are no errors from spelling mistakes. enum UnitType { case Fighter case Cleric case Mage } let
let unitPrice = (fighter: 15, cleric: 20, mage: 25)
var unitType = "cleric"
// 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
}
如何调用unitPrice.unitType
所以它等于单价。cleric(20)?听起来你真正要找的是字典,而不是元组。 请尝试以下操作:
let unitPrice = (fighter: 15, cleric: 20, mage: 25)
var unitType = "cleric"
// 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
}
听起来你真正想要的是一本字典,而不是元组。 请尝试以下操作:
let unitPrice = (fighter: 15, cleric: 20, mage: 25)
var unitType = "cleric"
// 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
}
如果我是对的,你不想在元组中添加unitType,对吗?没错,我不想。例如,我想使用变量而不是术语“cleric”调用unitPrice.cleric,尝试从其索引中提取值。索引从零开始。例如:unitPrice.1Ok,但是如果unitType=1,那么unitPrice.unitType仍然不工作如果我是对的,你不想在元组中添加unitType,对吗?没错,我不想。例如,我想使用变量而不是术语“cleric”调用unitPrice.cleric,尝试从其索引中提取值。索引从零开始。例如:unitPrice.1Ok,但是如果unitType=1,那么unitPrice.unitType仍然不起作用