Forked from JosephDuffy/Binding+mappedToBool.swift
Created
February 17, 2021 13:13
-
-
Save regexident/6c324463354a0cda321ad1faedcb302f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment