[O] Implement obj.apply {} like Kotlin

This commit is contained in:
Hykilpikonna
2021-01-17 16:34:20 -05:00
parent 7e4dc51da8
commit 2c5f28c97b
3 changed files with 22 additions and 5 deletions
+5 -2
View File
@@ -56,8 +56,11 @@ class AlarmActivator: UITabBarController
guard let alarm = alarms.listActivating.first else { return }
// Update alarm info
alarm.lastActivate = Date()
if alarm.oneTime { alarm.enabled = false }
alarm.apply {
$0.lastActivate = Date()
if $0.oneTime { $0.enabled = false }
}
alarms.localSave()
// Segue
+3 -3
View File
@@ -100,13 +100,13 @@ class Alarms: Codable
var list: [Alarm] = []
/// Save alarms to local storage
func localSave() -> Alarms { localStorage.setValue(JSON.stringify(list)!, forKey: "alarms"); return self }
func localSave() { localStorage.setValue(JSON.stringify(list)!, forKey: "alarms") }
/// Read alarms from local storage
func localRead() -> Alarms { list = JSON.parse([Alarm].self, localStorage.string(forKey: "alarms")!)!; return self }
func localRead() { list = JSON.parse([Alarm].self, localStorage.string(forKey: "alarms")!)! }
/// Read an alarm object from local storage
static func fromLocal() -> Alarms { return Alarms().localRead() }
static func fromLocal() -> Alarms { return Alarms().apply { $0.localRead() } }
/// Get enabled alarms
var listEnabled: [Alarm] { return list.filter { $0.enabled } }
+14
View File
@@ -77,3 +77,17 @@ extension TimeInterval
else { return "\(seconds)s" }
}
}
/// Apply like Kotlin
protocol HasApply {}
extension HasApply
{
@discardableResult
func apply(_ c: (Self) -> ()) -> Self
{
c(self)
return self
}
}
extension Alarm: HasApply {}
extension Alarms: HasApply {}