枚举的函数中是否可能有惰性行为?

时间:2019-08-03 17:53:14

标签: swift

Swift提供了非常方便的lazy var

但是,我想知道,我们能否为Enum的功能实现类似的惰性功能?

例如,

class Utils {
    static let userDataDirectory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
}

enum UserDataDirectory : String {
    case Extract = "extract"
    case Camera = "camera"
    case Mic = "mic"
    case Attachment = "attachment"
    case Recording = "recording"
    case RestoreAttachment = "restore_attachment"
    case RestoreRecording = "restore_recording"

    func get() -> URL {
        return Utils.userDataDirectory.appendingPathComponent(self.rawValue)
    }
}

是否有可能打开enum UserDataDirectory的{​​{1}}函数以具有懒惰的评估行为。

或者,由于getappendingPathComponent是恒定的,有没有一种方法可以避免每次评估Utils.userDataDirectory

1 个答案:

答案 0 :(得分:0)

您的意思是说您想要一个延迟评估的静态值。这很简单;添加静态缓存:

enum UserDataDirectory : String {
    // ...

    // Define storage
    private static var urls: [Self: URL] = [:]

    func url() -> URL {
        // Check the cache
        if let url = Self.urls[self] {
            return url
        } else {
            // Compute and cache
            let url = Utils.userDataDirectory.appendingPathComponent(self.rawValue)
            Self.urls[self] = url
            return url
        }
    }
}