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}}函数以具有懒惰的评估行为。
或者,由于get
和appendingPathComponent
是恒定的,有没有一种方法可以避免每次评估Utils.userDataDirectory
?
答案 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
}
}
}