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 is the difference between swift and ‘objective-c’ language?
Explain completion handler?
What is nil-coalescing operator?
In swift what is use of backticks while declaring a variable?
Is swift similar to c?
What is forced unwrapping? Why is it potentially unsafe?
What are the advantages of swift?
List the features of swift programming?
What do you do when you realize that your app is prone to crashing?
What are lazy stored properties, and how are they useful?
What is operation queue in swift?
Do loops swift?
What are structures in swift?
Which banks use swift?
What is optional binding?