Daily iOS
Swift

mutating and value types

Which line in this code fails to compile, and why?

struct Counter {
    var value = 0
    func increment() { value += 1 }
}
let c = Counter()
c.increment()
How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

A struct method treats self as immutable by default, so value += 1 errors; changing a property needs mutating, and then a let instance can't call it.

Share a question