简体   繁体   中英

Computed Property in Protocol Extension not giving desired result

I am trying to implement Stack in Swift language. So, I made a protocol Container and inherited it in another protocol Stack , now to keep track of number of elements in stack I introduced a computed variable count in Container Protocol and gave it a getter in extension of Container protocol. (I could keep a track of number of elements by arr.count , but I am exploring other ways to do the same) At the end, I pushed one element in the stack, but when I print the value of count it was still 0, why the value of count is not 1?

import UIKit
import Foundation

protocol Container{
    associatedtype Item
    var arr : [Item]{get set}
    var count : Int{get}
}

protocol Stack : Container {
    mutating func push(item : Item) -> ()
    mutating func pop() -> Item?
}

extension Container {
    var count : Int {
        get {
            return arr.count
        }
    }
}

struct MyStack<Element> : Stack {
    var count: Int
    
    typealias Item = Element
    var arr : [Element] = []
    
    mutating func push(item : Element) -> (){
        arr.append(item)
    }
    
    mutating func pop() -> Element? {
        if count == 0 {
            return nil
        }
        return arr[count - 1]
    }
}

var obj = MyStack<Int>(count : 0)
obj.push(item: 1)
print(obj.arr) // arr = [1]
print(obj.count) //count = 0 Why the value of count is not 1

The problem is that you are declaring count as a stored property on MyStack . Default implementations in protocols are only used by conforming types if the conforming type itself doesn't provide an implementation on its own.

So you need to remove the count property from MyStack and this way, the default count implementation from the Container protocol will be used.

struct MyStack<Element> : Stack {
    typealias Item = Element
    var arr : [Element] = []
    
    mutating func push(item : Element) -> (){
        arr.append(item)
    }
    
    mutating func pop() -> Element? {
        if count == 0 {
            return nil
        }
        return arr[count - 1]
    }
}

var obj = MyStack<Int>()
obj.push(item: 1)
print(obj.arr) // arr = [1]
print(obj.count) // 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM