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 swift stand for?
What is memory leak in swift?
What is swift module?
How proficient are you in objective-c and swift? Can you briefly describe their differences?
What is dynamic dispatch swift?
What is the usage of switch statement in swift language?
Do swift classes inherit from nsobject?
What are the best ways of achieving concurrency in ios?
How you define variables in swift?
How does swift achieve multiple inheritance?
What is encapsulation in swift?
What is forced unwrapping?