Why doesn't this code work?
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self += 42
}
}
var x:Int = 7
let y:Int = x.adjust()
here is what I get on XCODE
is there a way to make adjust() return Int without changing its definition in the protocol?
The Mutating Keyword : In order to modify the properties of a value type, you have to use the mutating keyword in the instance method. With this keyword, your method can then have the ability to mutate the values of the properties and write it back to the original structure when the method implementation ends.
The mutating. keyword is added to its definition to enable it to modify its properties." Posted 6 years ago by. The nice thing about Swift's value types is that you can decide whether they are immutable or mutable at the point you use them.
Yes, you can give adjust a return value. Define it to return an Int in the protocol and class, then have it return itself in the mutating method:
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust() -> Int
}
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() -> Int {
self += 42
return self
}
}
var x:Int = 7
let y:Int = x.adjust() //49
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With