Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Extension Computed Property Behavior
// To maintain state of extension computed property, use static variable
// A console logger
protocol ConsoleLoggable {
var logger: ConsoleLoggerProtocol { get }
}
extension ConsoleLoggable {
var logger: ConsoleLoggerProtocol {
print("New instance...")
return DefaultConsoleLogger()
}
}
protocol ConsoleLoggerProtocol {
func log()
}
struct DefaultConsoleLogger: ConsoleLoggerProtocol {
func log() {
print("CONSOLE log...")
}
}
// A file logger
protocol FileLoggable {
var logger: FileLoggerProtocol { get }
}
extension FileLoggable {
var logger: FileLoggerProtocol {
return DefaultFileLogger()
}
}
protocol FileLoggerProtocol {
func log()
}
struct DefaultFileLogger: FileLoggerProtocol {
func log() {
print("FILE log...")
}
}
// Test
struct LoggerTest: ConsoleLoggable {
//struct LoggerTest: FileLoggable, ConsoleLoggable {
func test() {
logger.log()
logger.log()
//clogger.log()
//flogger.log()
}
}
LoggerTest().test()
/**
New instance...
CONSOLE log...
New instance...
CONSOLE log...
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment