sriram hegde
sriram hegde

Reputation: 2471

Advanced Swift2 - Implementing Protocols in Class Vs Implementing Protocols in Struct

// Protocol

Protocol Movable {
  mutating func moveTo(p : CGPoint) 
}

While Implementing a Protocol in a Class here is the Syntax

Class Car : Movable {
 func moveTo(p : CGPoint) {...} 
}
Struct Shape : Movable {
 mutating func moveTo(p : CGPoint) {...} 
}

Now why do have to insert "mutating" in struct , whats it doing underneath.

Upvotes: 0

Views: 62

Answers (1)

gnasher729
gnasher729

Reputation: 52622

Because structs are by default assumed to be immutable, while class instances are assumed to be mutable. Therefore you don't need to mark a function that modifies a class instance, but you must mark a method that modifies a struct. Assume you wrote let myShape = Shape(). The compiler needs to know that it cannot let you call myShape.moveTo(...).

Upvotes: 1

Related Questions