Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a mutating function in an extension return Int using Swift?

Tags:

swift

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

enter image description here

is there a way to make adjust() return Int without changing its definition in the protocol?

like image 613
ielyamani Avatar asked Jun 08 '14 22:06

ielyamani


People also ask

How do you call a mutating function in Swift?

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.

What does the swift mutating keyword mean?

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.


1 Answers

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
like image 195
Connor Avatar answered Oct 11 '22 18:10

Connor