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 many types of closures are there in swift?
What is retain in swift?
Is swift written in c++?
What is difference between single and double, in swift?
What is de-initializer and how it is written in Swift?
How would you define variables and constants in swift programming language?
What is a swift class?
How proficient are you in objective-c and swift? Can you briefly describe their differences?
Is swift a functional language?
What is use of enum in swift?
What is tuple in swift?
What is enum in swift?