Vince O'Sullivan Vince O'Sullivan - 3 months ago 4x
Swift Question

Any ideas why MyStack doesn't conform to ProtoStack?

I have put together what should have been a simple piece of sample in an Xcode 8β2 playground. Unfortunately, I can't see why the

does not conform to the
. I'm sure it's something very simple but can't, for the life of me, see it.

protocol ProtoStack {

associatedtype ItemType

func push(item: ItemType)
func pop() -> ItemType
func isEmpty() -> Bool
func size() -> Int

struct MyStack: ProtoStack {

var contents = [Int]()

typealias ItemType = Int

mutating func push(item: Int) { contents.append(item) }
mutating func pop() -> Int { return contents.popLast()! }
func isEmpty() -> Bool { return contents.count == 0 }
func size() -> Int { return contents.count }


In order to conform to your ProtoStack protocol as it's currently written, your push and pop methods in your MyStack can't be mutating, as you cannot satisfy a non-mutating protocol requirement with a mutating struct/enum method. Therefore if you want these methods to be mutating, then you also need to mark them in the protocol as being so.

As the Swift language guide says (emphasis mine):

If you define a protocol instance method requirement that is intended to mutate instances of any type that adopts the protocol, mark the method with the mutating keyword as part of the protocol’s definition. This enables structures and enumerations to adopt the protocol and satisfy that method requirement.

A mutating method in a protocol requirement can either be satisfied by a mutating1 instance method in a value type (e.g a struct or enum) or a regular instance method in a class, as class instances can be mutated freely.

1. A mutating protocol requirement can also be satisfied by a non-mutating method in a value type, as this doesn't break the contract with the protocol (nothing depends on a mutation actually taking place within that method).