Skip to content

Instantly share code, notes, and snippets.

@casademora
Last active May 17, 2017 01:08
Show Gist options
  • Save casademora/3b784e57bd09c0bc9147 to your computer and use it in GitHub Desktop.
Save casademora/3b784e57bd09c0bc9147 to your computer and use it in GitHub Desktop.
Simple Outline for Cache layer in Swift
//: Playground - noun: a place where people can play
import UIKit
protocol DataSource {
func fetchValue() -> String?
}
protocol DataSourceCacheStrategy {
func retrieve<T>(from: [DataSource], using: DataSource -> T?) -> T?
}
struct DataSourceCache {
let strategy: DataSourceCacheStrategy
let localDataSource: DataSource
let remoteDataSource: DataSource
func fetch<T>(applyFunction: DataSource -> T?) -> T? {
let sources = [localDataSource, remoteDataSource]
return strategy.retrieve(sources, using: applyFunction)
}
}
struct BasicDataSourceCacheStrategy: DataSourceCacheStrategy {
func retrieve<T>(from: [DataSource], using: DataSource -> T?) -> T? {
for dataSource in from {
if let result = using(dataSource) {
return result
}
}
return nil
}
}
struct MoreFancyDataSourceCacheStrategy: DataSourceCacheStrategy {
func retrieve<T>(from: [DataSource], using: DataSource -> T?) -> T? {
let cacheValidation: T? -> Bool = { $0 != nil }
for dataSource in from {
let result = using(dataSource)
if cacheValidation(result) {
return result
}
}
return nil
}
}
struct LocalDataSource: DataSource {
func fetchValue() -> String? {
return nil // "from local source"
}
}
struct RemoteDataSource: DataSource {
func fetchValue() -> String? {
return "from remote source"
}
}
let strategy = BasicDataSourceCacheStrategy()
let cache = DataSourceCache(strategy: strategy, localDataSource: LocalDataSource(), remoteDataSource: RemoteDataSource())
let result = cache.fetch { $0.fetchValue() }
println("Result \(result)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment