Skip to content

Instantly share code, notes, and snippets.

@laevandus
Created November 3, 2020 07:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laevandus/3e2f5dc58643728980f66e65b98950ea to your computer and use it in GitHub Desktop.
Save laevandus/3e2f5dc58643728980f66e65b98950ea to your computer and use it in GitHub Desktop.
// MARK: View
struct PackageCombineModelView: View {
@StateObject var viewModel: ViewModel
var body: some View {
Form {
TextField("First name", text: $viewModel.firstName)
Text(viewModel.modelDescription)
}
}
}
// MARK: Model
extension PackageCombineModelView {
final class Package {
@Published var recipient = FullName()
// Other properties…
}
}
struct FullName {
var firstName: String = "A"
var lastName: String = "B"
}
// MARK: View Model
extension PackageCombineModelView {
final class ViewModel: ObservableObject {
private let package: Package
private var cancellables = [AnyCancellable]()
init(package: Package) {
self.package = package
// Model -> ViewModel
package.$recipient
.map(\.firstName)
.assign(to: &$firstName)
// ViewModel -> Model
$firstName
.dropFirst()
.removeDuplicates()
.assign(to: \.recipient.firstName, on: package)
.store(in: &cancellables)
}
@Published var firstName: String = ""
var modelDescription: String {
return String(describing: package.recipient)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment