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 Posted / 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 |
Post New Answer View All Answers
What are the half open range operators in swift?
What is forced unwrapping? Why is it potentially unsafe?
What are adapter and memento patterns?
Does swift have a garbage collector?
Is it worth learning swift 2019?
What is mutable and immutable in swift?
What is a delegate in swift?
How many types of closures are there in swift?
What is an optional in swift?
How to make a method or variable generics in swift?
What are the control transfer statements in swift?
What is mvvm in swift?
Can you explain completion handler?
Why do we use swift? Mention some advantages of swift?
How to convert nsmutablearray to swift array in swift?