Created
November 4, 2020 12:04
-
-
Save laevandus/ef3520206923ac6b42355bb63d0dbe28 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
| extension ContentView { | |
| final class ViewModel: ObservableObject { | |
| private let package: Package | |
| private var cancellables = [AnyCancellable]() | |
| init(package: Package) { | |
| self.package = package | |
| // Model -> View Model | |
| package.recipient.publisher(for: \.firstName) | |
| .assign(to: &$recipientFirstName) | |
| package.recipient.publisher(for: \.lastName) | |
| .assign(to: &$recipientLastName) | |
| package.recipient.publisher(for: \.postalAddress) | |
| .notifyObjectWillChange(objectWillChange) | |
| .store(in: &cancellables) | |
| package.publisher(for: \.contents) | |
| .notifyObjectWillChange(objectWillChange) | |
| .store(in: &cancellables) | |
| // View Model -> Model | |
| $recipientFirstName.dropFirst() | |
| .removeDuplicates() | |
| .assign(to: \.firstName, on: package.recipient) | |
| .store(in: &cancellables) | |
| $recipientLastName.dropFirst() | |
| .removeDuplicates() | |
| .assign(to: \.lastName, on: package.recipient) | |
| .store(in: &cancellables) | |
| } | |
| // Example of using published property | |
| @Published var recipientFirstName: String = "" | |
| @Published var recipientLastName: String = "" | |
| // Example of using bindings for propagating values | |
| var street: Binding<String> { | |
| let package = self.package | |
| return Binding<String>( | |
| get: { | |
| package.recipient.postalAddress.street | |
| }, | |
| set: { newValue in | |
| let postalAddress = package.recipient.postalAddress.mutableCopy() as! CNMutablePostalAddress | |
| postalAddress.street = newValue | |
| package.recipient.postalAddress = postalAddress | |
| } | |
| ) | |
| } | |
| var summary: String { | |
| let contents = package.contents | |
| .map({ "\($0.title) \($0.weight)" }) | |
| .joined(separator: ", ") | |
| return """ | |
| Recipient: \(package.recipient.firstName) \(package.recipient.lastName) | |
| Postal address: \(CNPostalAddressFormatter().string(from: package.recipient.postalAddress)) | |
| Contents: \(contents) | |
| """ | |
| } | |
| func addRandomItem() { | |
| let weight = Int.random(in: 200...300) | |
| let item = PackageContent(title: "Light bulb", weight: weight) | |
| package.contents.append(item) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment