簡體   English   中英

如何快速調用或訪問結構計算變量?

[英]How to call or access a struct computed variable in 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] 

嘗試這個。

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]

您應該從字典中刪除Item,可以使用key來做到這一點:

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

或者,如果您想從字典中獲取所有項目,則可以這樣枚舉:

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

通過致電:

myDict.iCost

您嘗試從根本不存在的Dictionary(不是Item)中獲取iCost屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM