Created
June 8, 2019 08:17
-
-
Save JanGorman/671bd7f2981072020ef85129c55d519d to your computer and use it in GitHub Desktop.
Expirable Swift @propertyWrapper
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
@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