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 optional binding?
What is argument label in swift?
List out what are the control transfer statements used in Swift?
Explain dictionary in swift.
What are the differences between a struct and a class?
Where can we test the apple iphone apps if we don’t have an ios device?
How can you add table view?
Is swift compiled or interpreted?
What do you do when you realize that your app is prone to crashing?
What are initializer in swift?
What is floating point number in swift? What are the different floating point numbers in swift?
Is swift like python?