-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Binding optional to non-optional and vice-versa (#12)
- Loading branch information
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
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 } | ||
) | ||
} | ||
} |