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
Can structs inherit swift?
What is difference between weak and strong in swift?
What is a protocol in swift?
What are the advantages of using swift for ios development?
What is lazy loading in ios swift?
Is swift memory safe?
What is the difference between nil and none in swift?
How should errors be handled in swift?
What is nsdictionary in swift?
What is the use of double question mark “??” In swift?
How can you define a base class in swift?
What are structures in swift?
Why swift is faster?
What is better swift or objective c?
Explain the different features of swift programming language?