Skip to content

Instantly share code, notes, and snippets.

@below
Last active February 27, 2020 18:27
Show Gist options
  • Save below/2fa8f9f4d7840ae37be897065d9bcc36 to your computer and use it in GitHub Desktop.
Save below/2fa8f9f4d7840ae37be897065d9bcc36 to your computer and use it in GitHub Desktop.
A simple combine sample. Good code? Could it be better?
class InOut: ObservableObject {
@Published var input = ""
@Published private (set) var output = "output"
private var publisher: AnyCancellable?
init() {
publisher = $input.map({
String($0.reversed())
}).assign(to: \.output, on: self)
}
}
@mmadeveloper
Copy link

You could avoid the force unwrap of publisher if you change it to an array and initialize it before as an empty array. Then append the cancellable that you created in init to this array. This way you could also manage several cancellables.

@below
Copy link
Author

below commented Feb 27, 2020

Updated with some helpful input

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment