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 benefit of using higher order functions?
Explain functions?
What is core data swift?
Is swift a language or framework?
Is swift a good language?
What is the difference between array and nsarray?
What is difference between single and double, in swift?
What are initializer in swift?
Is swift thread safe?
Is swift like java?
What is static function in swift?
What are the characteristics of switch?
What is a lazy var in swift?
How to create a tuple in swift?
What do you mean by the term “defer”?