bibin-jaimon / InterviewKit-iOS

5 stars 0 forks source link

How to create a generic protocol in Swift #13

Open bibin-jaimon opened 8 months ago

bibin-jaimon commented 8 months ago

We can create a generic protocol using associatedtype and typealias

protocol StackProtocol {
    associatedtype Element

    mutating func push(_ element: Element)
    mutating func pop() -> Element?
}

struct IntStack: StackProtocol {
    typealias Element = Int
    var stack = [Element]()

    mutating func push(_ element: Element) {
        stack.append(element)
    }

    mutating func pop() -> Element? {
        stack.popLast()
    }
}

struct StringStack: StackProtocol {
    typealias Element = String
    var stack: [Element] = []

    mutating func push(_ element: String) {
        stack.append(element)
    }

    mutating func pop() -> String? {
        stack.popLast()
    }

}