How to unwrap Binding with Optional in SwiftUI

Issue #677

The quick way to add new properties without breaking current saved Codable is to declare them as optional. For example if you use EasyStash library to save and load Codable models.

1
2
3
4
5
6
7
import SwiftUI

struct Input: Codable {
var bundleId: String = ""

// New props
var notificationId: String?

This new property when using dollar syntax $input.notificationId turn into Binding with optional Binding<Strting?> which is incompatible in SwiftUI when we use Binding.

1
2
3
4
struct MaterialTextField: View {
let placeholder: String
@Binding var text: String
}

The solution here is write an extension that converts Binding<String?> to Binding<String>

1
2
3
4
5
6
7
8
9
10
11
12
extension Binding where Value == String? {
func toNonOptional() -> Binding<String> {
return Binding<String>(
get: {
return self.wrappedValue ?? ""
},
set: {
self.wrappedValue = $0
}
)
}
}

so we can use them as normal

1
MaterialTextField(text: $input.notificationId.toNonOptional())

Comments