簡體   English   中英

協議擴展中的計算屬性未給出預期結果

[英]Computed Property in Protocol Extension not giving desired result

我正在嘗試用 Swift 語言實現 Stack。 因此,我創建了一個協議Container並在另一個協議Stack中繼承它,現在為了跟蹤堆棧中的元素數量,我在Container Protocol 中引入了一個計算變量count ,並在Container協議的擴展中給了它一個 getter。 (我可以通過arr.count跟蹤元素的數量,但我正在探索其他方法來做同樣的事情)最后,我將一個元素壓入堆棧,但是當我打印count的值時它仍然是 0 ,為什么count的值不是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

問題是您將count聲明為MyStack上的存儲屬性。 如果符合類型本身不提供自己的實現,則協議中的默認實現僅由符合類型使用。

因此,您需要從MyStack中刪除count屬性,這樣,將使用Container協議中的默認count實現。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM