user6510422 user6510422 - 4 months ago 8
iOS Question

Keyword var required in front of struct value type when used as a parameter in a function

Why is the keyword var required in front of a struct's value type parameter when used in a function?

struct MyValueType {
var name:String
var assignment:String
var grade:Int
}

class MyReferenceType{
var name:String
var assignment:String
var grade:Int
init(name:String,assignment:String,grade:Int){
self.name = name
self.assignment = assignment
self.grade = grade
}
}

var myRef = MyReferenceType(name:"Jon",assignment:"Math Test 1",grade:90)

print(myRef.assignment)
func extraCreditReferenceType(ref:MyReferenceType,extraCredit:Int){
ref.grade += extraCredit
}

func extraCreditValueType(var val:MyValueType,extraCredit:Int){
val.grade += extraCredit
}

var ref = MyReferenceType(name:"Jon",assignment:"Math Test 1",grade:90)

print(ref.grade)
extraCreditReferenceType(ref,extraCredit:5)
print("Reference: \(ref.name) - \(ref.grade)")



var val = MyValueType(name:"Jon",assignment:"Math Test 1",grade:90)
extraCreditValueType(val,extraCredit:5)
print("Value: \(val.name) - \(val.grade)")


The line in question is the following function:

func extraCreditValueType(var val:MyValueType,extraCredit:Int){
val.grade += extraCredit
}


By removing the keyword var, the code won't compile.

Answer

Because structs as parameters are let types by default, and because you are making changes to the struct in the function, it would have to be a var

It seems the var in the parameter is not going to be allowed in swift 3.0, so will have to remove it anyway eventually

Also your extraCreditValueType func is not going to do what you think it does, since structs are pass by value, the parameter val is not the same as the val on the outside of the function, therefore making changes to it in the function will not have an effect outside the function. you should either make MyValueType a class (and prob change the name) or return the val from the function to be used outside of the function