Files
damus/damus/Util/Extensions/Binding+.swift
OlegAba 18449c8c0d Fix repost button sometimes not working
Changelog-Fixed: Fix repost button sometimes not working
Closes: #738
2023-03-13 12:54:13 -06:00

50 lines
1.8 KiB
Swift

//
// Binding+.swift
// damus
//
// Created by Oleg Abalonski on 3/5/23.
// Ref: https://josephduffy.co.uk/posts/mapping-optional-binding-to-bool
import os.log
import SwiftUI
extension Binding where Value == Bool {
/// Creates a binding by mapping an optional value to a `Bool` that is
/// `true` when the value is non-`nil` and `false` when the value is `nil`.
///
/// When the value of the produced binding is set to `false` the value
/// of `bindingToOptional`'s `wrappedValue` is set to `nil`.
///
/// Setting the value of the produce binding to `true` does nothing and
/// will log an error.
///
/// - parameter bindingToOptional: A `Binding` to an optional value, used to calculate the `wrappedValue`.
public init<Wrapped>(mappedTo bindingToOptional: Binding<Wrapped?>) {
self.init(
get: { bindingToOptional.wrappedValue != nil },
set: { newValue in
if !newValue {
bindingToOptional.wrappedValue = nil
} else {
os_log(
.error,
"Optional binding mapped to optional has been set to `true`, which will have no effect. Current value: %@",
String(describing: bindingToOptional.wrappedValue)
)
}
}
)
}
}
extension Binding {
/// Returns a binding by mapping this binding's value to a `Bool` that is
/// `true` when the value is non-`nil` and `false` when the value is `nil`.
///
/// When the value of the produced binding is set to `false` this binding's value
/// is set to `nil`.
public func mappedToBool<Wrapped>() -> Binding<Bool> where Value == Wrapped? {
return Binding<Bool>(mappedTo: self)
}
}