Created
January 3, 2019 14:52
-
-
Save nicholasspencer/9d0b56727baf1448493f8e460d278b28 to your computer and use it in GitHub Desktop.
On-demand nil coalescing infix operator
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 | |
infix operator ??=: NilCoalescingPrecedence | |
func ??= <T>(left: inout T?, right: T) -> T? { | |
left = left ?? right | |
return left | |
} | |
class MyClass { | |
private var _onDemand: Date? | |
var onDemand: Date? { | |
get { return _onDemand ??= Date() } | |
set { _onDemand = newValue } | |
} | |
} | |
let myClass = MyClass() | |
let formatter = DateFormatter() | |
formatter.dateFormat = "y-MM-dd H:m:ss.SSSS" | |
if let onDemand = myClass.onDemand { | |
print(formatter.string(from: onDemand)) // 2019-01-03 8:51:52.9600 | |
} | |
myClass.onDemand = nil | |
if let onDemand = myClass.onDemand { | |
print(formatter.string(from: onDemand)) // 2019-01-03 8:51:52.9620 | |
} | |
myClass.onDemand = Date().addingTimeInterval(84000) | |
if let onDemand = myClass.onDemand { | |
print(formatter.string(from: onDemand)) // 2019-01-04 8:51:52.9620 | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment