user2725255
user2725255

Reputation: 121

Mutating in Structure Swift Same function Name

Still trying out swift, and I came across this problem (not sure if it really classifies as one)

So we have a protocol, and a structure that inherits it.

protocol ExampleProtocol {
 var simpleDescription: String { get }
 func adjust()
}

struct SimpleStructure : ExampleProtocol{
   var simpleDescription = "A simple structure"

   mutating func adjust() {
      simpleDescription += " (adjusted)"
   }

   func adjust() { //I created this second method just to conform to the protocol
   }
}


var b = SimpleStructure()
b.adjust() //This generates a compiler error mentioning Ambiguity (Correct)

Question is how do I call the mutating adjust() not the adjust from the protocol. i.e. I know if I declare b as a protocol and initialized it to the struct it will call adjust from protocol, but how do I call the first adjust ? or is it not possible? Or Am I using it wrongly ?

Cheers,

Upvotes: 0

Views: 311

Answers (1)

Antonio
Antonio

Reputation: 72760

Your code doesn't compile, but the error is in redefining the adjust method by adding the mutating attribute - that doesn't create an overloaded version of adjust.

In my opinion this is the correct code:

protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
}

struct SimpleStructure : ExampleProtocol{
    var simpleDescription = "A simple structure"

    mutating func adjust() {
        simpleDescription += " (adjusted)"
    }
}

which means: you have to define the adjust function as mutating in the protocol.

Upvotes: 1

Related Questions