gpt4 book ai didi

arrays - 如何快速调用或访问结构计算变量?

转载 作者:搜寻专家 更新时间:2023-11-01 07:27:18 25 4
gpt4 key购买 nike

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] 

最佳答案

试试这个。

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]

关于arrays - 如何快速调用或访问结构计算变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35156125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com