如何在swift中调用或访问struct computed变量?

时间:2016-02-02 14:29:15

标签: arrays swift

struct Item {
    var iQuantity : Int
    var iPrice : Int
    var iCost : Int { return iQuantity*iPrice }
}

let item1 = Item(iQuantity: 1, iPrice: 20)
let item2 = Item(iQuantity: 3, iPrice: 30)

let myDict = ["dog": item1, "cat": item2]

Array(myDict.values   // only have price / quantity
Array(myDict.iCost)  // want something like this not working
// want array of all cost( P*Q )  for each item => [20,90] 

2 个答案:

答案 0 :(得分:1)

试试这个。

struct Item {
    var iQuantity : Int
    var iPrice : Int
    var iCost : Int { return iQuantity*iPrice }
}

let item1 = Item(iQuantity: 1, iPrice: 20)
let item2 = Item(iQuantity: 3, iPrice: 30)

let myDict = ["dog": item1, "cat": item2]

let myCosts = myDict.map( { $0.1.iCost } ) // [90, 20]

正如评论员@ konrad.bajtyngier所说,你的myDict是一本字典。当然,这意味着项目的顺序是未定义的,这可能不是您所期望的。您可能希望将数据结构重新定义为:

struct Item {
    var iName: String
    var iQuantity : Int
    var iPrice : Int
    var iCost : Int { return iQuantity*iPrice }
}

let item1 = Item(iName: "Dog", iQuantity: 1, iPrice: 20)
let item2 = Item(iName: "Cat", iQuantity: 3, iPrice: 30)

let myArray = [item1, item2]

let myCosts = myArray.map( { $0.iCost } ) // [20, 90]

答案 1 :(得分:1)

你应该从字典中获取你的项目,你可以使用密钥来做到这一点:

let iCost = myDict["cat"]?.iCost

或者如果你想从字典中获取所有项目,你可以这样枚举:

for (key, item) in myDict {
    print("\(key) - \(item), iCost: \(item.iCost)")
}

致电:

myDict.iCost

你试图从字典(而不是Item)中获取iCost属性,而这种属性根本就不存在。