Skip to content

Instantly share code, notes, and snippets.

@JanGorman
Created June 8, 2019 08:17
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JanGorman/671bd7f2981072020ef85129c55d519d to your computer and use it in GitHub Desktop.
Save JanGorman/671bd7f2981072020ef85129c55d519d to your computer and use it in GitHub Desktop.
Expirable Swift @propertyWrapper
@propertyWrapper
struct Expirable<Value: ExpressibleByNilLiteral> {
let duration: TimeInterval
private var expirationDate = Date()
private var innerValue: Value = nil
private var hasExpired: Bool {
expirationDate < Date()
}
init(duration: TimeInterval) {
self.duration = duration
}
var value: Value {
get {
hasExpired ? nil : innerValue
}
set {
expirationDate = Date().addingTimeInterval(duration)
innerValue = newValue
}
}
}
struct Tokens {
@Expirable(duration: 3) static var authentication: String?
}
Tokens.authentication = "abc"
sleep(2)
Tokens.authentication // "abc"
sleep(2)
Tokens.authentication // nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment