Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I assign a value to a Struct member?

Tags:

struct

swift

struct Item {
    var name:String?
    var type:String?
    var value:Int?
    var tag:Int?
}
...
...
 let petItem = Item(name:petName!.uppercaseString, type:petType, value:0, tag:0)
 self.statusLabel.hidden = false
 if addItem(petItem) {
    self.statusLabel.text = petName! + " successfully added."
    self.textField.becomeFirstResponder()
 } else {
    self.statusLabel.text = "Sorry, Pet couldn't be added."
 }
...
...
func addItem(petItem:Item) -> Bool {
    if treeIsFull() {
        println("Tree is full\n")
    } else {
        petItem.name = "turkey" <--- *** error ***
...

I can't assign values to any members of a struct.
I get the following error:

Error: Cannot assign to 'name' to 'petItem'.

Is there a remedy or must I assign ALL values during instance creation?

like image 333
Frederick C. Lee Avatar asked Aug 15 '14 22:08

Frederick C. Lee


1 Answers

The reason you're seeing that error is that petItem is immutable (you can't change it) inside addItem. If you want to change the instance you pass in, you'll need to declare the function this way:

func addItem(var petItem:Item) -> Bool { ...

Unfortunately, now you have another error, since the petItem variable you created initally with let is immutable. So change that to var and off you go:

var petItem = Item(name:petName!.uppercaseString, type:petType, value:0, tag:0)

So now you can run your code, and you might realize that the name you set in addItem() isn't making it out to your petItem variable. What happened? In Swift struct instances are passed to functions by value, so nothing that happens to a parameter in the function affects the original variable, unless the parameter is declared as inout. So let's do that:

func addItem(inout petItem:Item) -> Bool { ...

and you'll need to change your call to show that you know this parameter can be modified:

if addItem(&petItem) { ...
like image 124
Nate Cook Avatar answered Sep 28 '22 15:09

Nate Cook