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 type aliasing in swift?
What are type methods in swift?
What is a guard statement?
What is selector swift?
How do you make a bridging header in swift?
What are the tools that are required to develop ios applications?
What is nested function in swift?
What is closure in swift?
What is the use of static keyword in swift?
What is lazy loading in ios swift?
Is swift worth learning 2019?
What is a swift protocol?