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
Why does apple use swift?
How many access levels are present in swift?
Why swift is faster?
What is difference between if and guard in swift?
What is instance variable in swift?
What is nil-coalescing operator?
Explain enum?
Is ios written in swift?
What are the differences between a struct and a class?
Does swift have a garbage collector?
How do I create a swift file in xcode?
What is the characteristics of switch in swift?
What is dynamic member lookup swift?
How will you connect ui?
Explain the usage of class and benefits of inheritance.