簡體   English   中英

協議中的計算屬性獲取器被調用的次數超過了所需次數

[英]Computed Property getter in protocol called more times than required

我在協議擴展中創建了一個私有變量,並使用該私有變量來獲取對象的實例。

即使我叫了一次,吸氣劑也叫了兩次。 我准備了一個游樂場來證明這一點。

下面是代碼:

class LoggingService {
    func sayWorld() {
        print("world")
    }
}

protocol LoggerType {
    func sayWorld()
}

extension LoggerType {
    private var loggerInstance: LoggingService {
        print("init")
        return LoggingService()
    }

    func sayWorld() {
        self.loggerInstance.sayWorld()
    }
}

class ViewMock: LoggerType {
    init() {

    }
}

let viewObj = ViewMock()
viewObj.sayWorld()

看看跑步場

在此處輸入圖片說明

需要對此行為進行一些解釋。

正如@Hamish在評論中所解釋的那樣,在一個已編譯的項目中,它按預期方式工作,即,僅被調用一次。

我仍然想知道為什么在操場上會發生這種情況。 所以,如果有人有什么要分享的,我想聽聽。

暫無
暫無

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

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