Skip to content

Commit

Permalink
Binding optional to non-optional and vice-versa (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
luizmb authored Sep 14, 2020
1 parent e05ff17 commit 6909a2c
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions Sources/UIExtensions/Extensions/Binding+Optional.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
//
// Binding+ToOptional.swift
// UIExtensions
//
// Created by Luiz Rodrigo Martins Barbosa on 14.09.20.
// Copyright © 2020 Lautsprecher Teufel GmbH. All rights reserved.
//

import SwiftUI

extension Binding {
/// Transforms a `Binding<Value>` in a `Binding<Optional<Value>>`. This is useful when your
/// internal binding allows optional values to be read and set, but your parent control only
/// offers binding to a non-Optional type.
///
/// You can optionally provide a closure to be called when the inner component sets the wrapped
/// value no nil, so your parent control can act on that accordingly.
public func toOptional(onSetToNil: @escaping () -> Void = { }) -> Binding<Value?> {
Binding<Value?>(
get: { self.wrappedValue },
set: { newValue in
guard let newValue = newValue else {
onSetToNil()
return
}
self.wrappedValue = newValue
}
)
}
}

extension Binding {
/// Transforms a `Binding<Optional<Value>>` in a `Binding<Value>`. This is useful when your
/// internal binding requires a non-nil value, but your parent control only offers binding
/// to an Optional type. You must provide a default fallback for when reading a nil value.
public func toNonOptional<V>(default fallback: V) -> Binding<V> where Value == V? {
Binding<V>(
get: { self.wrappedValue ?? fallback },
set: { self.wrappedValue = $0 }
)
}
}

0 comments on commit 6909a2c

Please sign in to comment.