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 |
How to make a method or variable generics in swift?
What is floating point number in swift? What are the different floating point numbers in swift?
What will you do if your app is prone to crashing?
How multiple line comment can be written in swift?
What are the tools that are required to develop ios applications?
What are the control transfer statements that are used in ios swift?
What is atomic swift?
What are swift properties?
How do I create a bridge header in swift 4?
Explain some design patterns which we normally use during the app development.
Why does apple use swift?
What is a static variable swift?