damus

nostr ios client
git clone git://jb55.com/damus
Log | Files | Refs | README | LICENSE

Binding+.swift (1824B)


      1 //
      2 //  Binding+.swift
      3 //  damus
      4 //
      5 //  Created by Oleg Abalonski on 3/5/23.
      6 //  Ref: https://josephduffy.co.uk/posts/mapping-optional-binding-to-bool
      7 
      8 import os.log
      9 import SwiftUI
     10 
     11 extension Binding where Value == Bool {
     12     /// Creates a binding by mapping an optional value to a `Bool` that is
     13     /// `true` when the value is non-`nil` and `false` when the value is `nil`.
     14     ///
     15     /// When the value of the produced binding is set to `false` the value
     16     /// of `bindingToOptional`'s `wrappedValue` is set to `nil`.
     17     ///
     18     /// Setting the value of the produce binding to `true` does nothing and
     19     /// will log an error.
     20     ///
     21     /// - parameter bindingToOptional: A `Binding` to an optional value, used to calculate the `wrappedValue`.
     22     public init<Wrapped>(mappedTo bindingToOptional: Binding<Wrapped?>) {
     23         self.init(
     24             get: { bindingToOptional.wrappedValue != nil },
     25             set: { newValue in
     26                 if !newValue {
     27                     bindingToOptional.wrappedValue = nil
     28                 } else {
     29                     os_log(
     30                         .error,
     31                         "Optional binding mapped to optional has been set to `true`, which will have no effect. Current value: %@",
     32                         String(describing: bindingToOptional.wrappedValue)
     33                     )
     34                 }
     35             }
     36         )
     37     }
     38 }
     39 
     40 extension Binding {
     41     /// Returns a binding by mapping this binding's value to a `Bool` that is
     42     /// `true` when the value is non-`nil` and `false` when the value is `nil`.
     43     ///
     44     /// When the value of the produced binding is set to `false` this binding's value
     45     /// is set to `nil`.
     46     public func mappedToBool<Wrapped>() -> Binding<Bool> where Value == Wrapped? {
     47         return Binding<Bool>(mappedTo: self)
     48     }
     49 }