Created
June 28, 2016 17:04
-
-
Save marcinczenko/d448780afaa499ba683d5160b9aae1d3 to your computer and use it in GitHub Desktop.
A Swift playground for the blog post "Around TypeErasure in Swift"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
protocol Logger { | |
associatedtype LoggerItemType | |
func log(item: LoggerItemType) | |
} | |
struct AnyLogger<LoggerItemType> : Logger { | |
let _log: LoggerItemType -> () | |
init<BaseType: Logger where BaseType.LoggerItemType == LoggerItemType>(base: BaseType) { | |
_log = base.log | |
} | |
func log(item: LoggerItemType) { | |
_log(item) | |
} | |
} | |
struct IntLogger: Logger { | |
func log(item: Int) { | |
print("IntLogger: \(item)") | |
} | |
} | |
struct Process<T> { | |
let logger: AnyLogger<T> | |
} | |
let process = Process(logger: AnyLogger(base: IntLogger())) | |
process.logger.log(24) | |
protocol LoggerProvider { | |
associatedtype LoggerType | |
func get() -> LoggerType | |
} | |
struct AnyLoggerProvider<LoggerType>: LoggerProvider { | |
let _get: () -> LoggerType | |
init<BaseType: LoggerProvider where BaseType.LoggerType == LoggerType>(base: BaseType) { | |
_get = base.get | |
} | |
func get() -> LoggerType { | |
return _get() | |
} | |
} | |
struct IntLoggerProvider: LoggerProvider { | |
let intLogger: IntLogger | |
func get() -> IntLogger { | |
return intLogger | |
} | |
} | |
struct Process2<T> { | |
let loggerProvider: AnyLoggerProvider<T> | |
} | |
let process2 = Process2(loggerProvider: AnyLoggerProvider(base: IntLoggerProvider(intLogger: IntLogger()))) | |
process2.loggerProvider.get().log(24) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment