How to assign a value to a Struct member?

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 not assign values ​​to any elements of the structure.
I get the following error:

Error: Unable to name 'petItem'.

Is there a tool or should I assign ALL values ​​at the time of instantiation?

+8
struct swift
source share
1 answer

The reason you see this error is because petItem is immutable (you cannot change it) inside addItem . If you want to change the instance you are passing, you need to declare the function as follows:

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

Unfortunately, now you have one more error, since the variable petItem that you created initally with let is unchanged. So change this to var and release:

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

So now you can run your code, and you can understand that the name set to addItem() does not output it to the variable petItem . What happened? In Swift struct instances are passed to functions by value, so nothing that happens to a parameter in a function affects the original variable unless the parameter is declared as inout . So do this:

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

and you will need to change your call to show that you know that this parameter can be changed:

 if addItem(&petItem) { ... 
+8
source share

All Articles