This question belongs to Swift Programming Language , specifically the objective covering structs, properties, and initializers .
In the struct, both the property and the initializer parameter are named age:
struct person {
var age: Int
init(age: Int) {
self.age = age
}
}
Here, age inside the initializer could refer to either the property of the struct or the parameter passed into the initializer. Swift uses self.age to clearly mean the property that belongs to the current instance , while plain age refers to the initializer parameter . So self.age = age means: assign the parameter value to the instance property.
That is why C is correct. The keyword self is required here to remove ambiguity between two identifiers with the same name.
The other options are incorrect:
A is wrong because self here is not pointing to the parameter; it points to the instance property.
B is wrong because self is not always required in every initializer assignment. It is specifically needed here because of the naming conflict.
D is wrong because whether the property has a default value is not the reason self is needed in this example.
So the correct answer is C. self is needed to distinguish between the property and the parameter with the same name.
Submit