JPC
JPC

Reputation: 5173

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] 

Upvotes: 1

Views: 91

Answers (2)

Grimxn
Grimxn

Reputation: 22487

Try this.

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]

As the commentator @konrad.bajtyngier says, your myDict is a dictionary. What that means, of course, is that the order of items is undefined, which may not be what you expect. You may wish to redefine your data structures to be as follows:

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]

Upvotes: 1

Greg
Greg

Reputation: 25459

You should get your Item off dictionary, you can use key to do that:

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

or if you want to get all Items from dictionary you can enumerate like that:

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

By calling:

myDict.iCost

you trying to get iCost property from Dictionary (not Item) which simply doesn't exist.

Upvotes: 1

Related Questions