The following code snippet results in a compile time error:
struct IntStack {
var items = [Int]()
func add(x: Int) {
items.append(x) // Compile time error here.
}
}
Explain why a compile time error occurs. How can you fix it?
Answer / iosraj
Structures are value types. By default, the properties of a value type cannot be modified from within its instance methods.
However, you can optionally allow such modification to occur by declaring the instance methods as ‘mutating’; e.g.:
struct IntStack {
var items = [Int]()
mutating func add(x: Int) {
items.append(x) // All good!
}
}
| Is This Answer Correct ? | 0 Yes | 0 No |
What is property observer in swift?
How much do swift developers make?
What are the different collection types available in swift?
What is a tuple in swift?
What is thread in swift?
What is an in-out parameter in swift?
Who calls the main function of our app during the app launch cycle?
How can you prioritize the usability of the demand process?
Is swift a functional language?
How do I add a header in swift?
Is swift faster than java?
Is swift an oop?