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 are methods in swift?
What are the various ways to unwrap an optional in swift?
What are floating point numbers? How many types of floating number are there?
Explain dictionary in swift.
Why is inheritance not desirable in swift?
What is core data swift?
How can you define a base class in swift?
What is asynchronous in swift?
What are swift properties?
Is swift an oop?
Who calls the main function of our app during the app launch cycle?
What are the two main integer types in swift?