Small 2-way binding for Swift












0














I recently started Swift and iOS development. After checking this cool tutorial for writing a small library for 2-way binding between views and data model, I decided to improve and simplify binding part. So I wrote a small observer/binder classes (based on idea on mentioned post, observer class is almost identical) to simplify binding. It works as expected, but since I'm new to iOS and Swift, I want someone to check if there is any crucial problems with my binding class. Here are classes:



class Observable<Object> {
typealias ObservableDelegate = (Object)->Void

var value: Object? {
didSet {
if let value = value {
notify(newValue: value)
}
}
}

private var observers = [ObservableDelegate]()

public init(_ value: Object? = nil) {
self.value = value
}

func addObserver(_ delegate: @escaping ObservableDelegate) {
observers.append(delegate)
}

private func notify(newValue value: Object) {
for delegate in observers {
delegate(value)
}
}
}

class ViewBindings {
private class BindingEventHandler: NSObject {
typealias BindingEventHandlerDelegate = () -> Void

let target: BindingEventHandlerDelegate

init(_ delegate: @escaping BindingEventHandlerDelegate) {
target = delegate
super.init()
}

@IBAction func valueChanged() {
self.target()
}
}

private var bindings = [BindingEventHandler]()

func bind<KeyRoot,Value>(_ obj: NSObject, from: ReferenceWritableKeyPath<KeyRoot,Value>, to: Observable<Value>) where Value: Equatable {
observeBind(obj, from: from, to: to)

if let control = obj as? UIControl {
let handler = BindingEventHandler {
[weak obj, weak to] in
if let _to = to {
if let val = (obj as? KeyRoot)?[keyPath: from], _to.value != val {
_to.value = val
}
}
}

bindings.append(handler)
control.addTarget(handler, action: #selector(BindingEventHandler.valueChanged), for: [.editingChanged, .valueChanged])
}
}

func observeBind<KeyRoot,Value>(_ obj: NSObject, from: ReferenceWritableKeyPath<KeyRoot,Value>, to: Observable<Value>) where Value: Equatable {
to.addObserver {
value in
DispatchQueue.main.async {
[weak obj] in
(obj as? KeyRoot)?[keyPath: from] = value
}
}
}
}


And here is a simple use of my ViewBindings class:



class ViewController: UIViewController {
@IBOutlet weak var textfield: UITextField!
@IBOutlet weak var label: UILabel!

let v1 = Observable<String?>()
let binds = ViewBindings()

override func viewDidLoad() {
super.viewDidLoad()

binds.bind(textfield, from: UITextField.text, to: v1)
binds.bind(label, from: UILabel.text, to: v1)
}

@IBAction func btnpressed(_ sender: Any) {
v1.value = "hello"
}
}


Improvements in comparison with original post




  1. In original implementation, you needed to extend control classes to conform to Bindable protocol, but it is not needed here.

  2. You can add multiple bindings for 1 control easily here (currently bind one time and observeBind multiple times.


I have not added methods for removing binding yet, but what do you think about usability of current class using KeyPath? any obvious problem with this class?









share









New contributor




Afshin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

























    0














    I recently started Swift and iOS development. After checking this cool tutorial for writing a small library for 2-way binding between views and data model, I decided to improve and simplify binding part. So I wrote a small observer/binder classes (based on idea on mentioned post, observer class is almost identical) to simplify binding. It works as expected, but since I'm new to iOS and Swift, I want someone to check if there is any crucial problems with my binding class. Here are classes:



    class Observable<Object> {
    typealias ObservableDelegate = (Object)->Void

    var value: Object? {
    didSet {
    if let value = value {
    notify(newValue: value)
    }
    }
    }

    private var observers = [ObservableDelegate]()

    public init(_ value: Object? = nil) {
    self.value = value
    }

    func addObserver(_ delegate: @escaping ObservableDelegate) {
    observers.append(delegate)
    }

    private func notify(newValue value: Object) {
    for delegate in observers {
    delegate(value)
    }
    }
    }

    class ViewBindings {
    private class BindingEventHandler: NSObject {
    typealias BindingEventHandlerDelegate = () -> Void

    let target: BindingEventHandlerDelegate

    init(_ delegate: @escaping BindingEventHandlerDelegate) {
    target = delegate
    super.init()
    }

    @IBAction func valueChanged() {
    self.target()
    }
    }

    private var bindings = [BindingEventHandler]()

    func bind<KeyRoot,Value>(_ obj: NSObject, from: ReferenceWritableKeyPath<KeyRoot,Value>, to: Observable<Value>) where Value: Equatable {
    observeBind(obj, from: from, to: to)

    if let control = obj as? UIControl {
    let handler = BindingEventHandler {
    [weak obj, weak to] in
    if let _to = to {
    if let val = (obj as? KeyRoot)?[keyPath: from], _to.value != val {
    _to.value = val
    }
    }
    }

    bindings.append(handler)
    control.addTarget(handler, action: #selector(BindingEventHandler.valueChanged), for: [.editingChanged, .valueChanged])
    }
    }

    func observeBind<KeyRoot,Value>(_ obj: NSObject, from: ReferenceWritableKeyPath<KeyRoot,Value>, to: Observable<Value>) where Value: Equatable {
    to.addObserver {
    value in
    DispatchQueue.main.async {
    [weak obj] in
    (obj as? KeyRoot)?[keyPath: from] = value
    }
    }
    }
    }


    And here is a simple use of my ViewBindings class:



    class ViewController: UIViewController {
    @IBOutlet weak var textfield: UITextField!
    @IBOutlet weak var label: UILabel!

    let v1 = Observable<String?>()
    let binds = ViewBindings()

    override func viewDidLoad() {
    super.viewDidLoad()

    binds.bind(textfield, from: UITextField.text, to: v1)
    binds.bind(label, from: UILabel.text, to: v1)
    }

    @IBAction func btnpressed(_ sender: Any) {
    v1.value = "hello"
    }
    }


    Improvements in comparison with original post




    1. In original implementation, you needed to extend control classes to conform to Bindable protocol, but it is not needed here.

    2. You can add multiple bindings for 1 control easily here (currently bind one time and observeBind multiple times.


    I have not added methods for removing binding yet, but what do you think about usability of current class using KeyPath? any obvious problem with this class?









    share









    New contributor




    Afshin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.























      0












      0








      0







      I recently started Swift and iOS development. After checking this cool tutorial for writing a small library for 2-way binding between views and data model, I decided to improve and simplify binding part. So I wrote a small observer/binder classes (based on idea on mentioned post, observer class is almost identical) to simplify binding. It works as expected, but since I'm new to iOS and Swift, I want someone to check if there is any crucial problems with my binding class. Here are classes:



      class Observable<Object> {
      typealias ObservableDelegate = (Object)->Void

      var value: Object? {
      didSet {
      if let value = value {
      notify(newValue: value)
      }
      }
      }

      private var observers = [ObservableDelegate]()

      public init(_ value: Object? = nil) {
      self.value = value
      }

      func addObserver(_ delegate: @escaping ObservableDelegate) {
      observers.append(delegate)
      }

      private func notify(newValue value: Object) {
      for delegate in observers {
      delegate(value)
      }
      }
      }

      class ViewBindings {
      private class BindingEventHandler: NSObject {
      typealias BindingEventHandlerDelegate = () -> Void

      let target: BindingEventHandlerDelegate

      init(_ delegate: @escaping BindingEventHandlerDelegate) {
      target = delegate
      super.init()
      }

      @IBAction func valueChanged() {
      self.target()
      }
      }

      private var bindings = [BindingEventHandler]()

      func bind<KeyRoot,Value>(_ obj: NSObject, from: ReferenceWritableKeyPath<KeyRoot,Value>, to: Observable<Value>) where Value: Equatable {
      observeBind(obj, from: from, to: to)

      if let control = obj as? UIControl {
      let handler = BindingEventHandler {
      [weak obj, weak to] in
      if let _to = to {
      if let val = (obj as? KeyRoot)?[keyPath: from], _to.value != val {
      _to.value = val
      }
      }
      }

      bindings.append(handler)
      control.addTarget(handler, action: #selector(BindingEventHandler.valueChanged), for: [.editingChanged, .valueChanged])
      }
      }

      func observeBind<KeyRoot,Value>(_ obj: NSObject, from: ReferenceWritableKeyPath<KeyRoot,Value>, to: Observable<Value>) where Value: Equatable {
      to.addObserver {
      value in
      DispatchQueue.main.async {
      [weak obj] in
      (obj as? KeyRoot)?[keyPath: from] = value
      }
      }
      }
      }


      And here is a simple use of my ViewBindings class:



      class ViewController: UIViewController {
      @IBOutlet weak var textfield: UITextField!
      @IBOutlet weak var label: UILabel!

      let v1 = Observable<String?>()
      let binds = ViewBindings()

      override func viewDidLoad() {
      super.viewDidLoad()

      binds.bind(textfield, from: UITextField.text, to: v1)
      binds.bind(label, from: UILabel.text, to: v1)
      }

      @IBAction func btnpressed(_ sender: Any) {
      v1.value = "hello"
      }
      }


      Improvements in comparison with original post




      1. In original implementation, you needed to extend control classes to conform to Bindable protocol, but it is not needed here.

      2. You can add multiple bindings for 1 control easily here (currently bind one time and observeBind multiple times.


      I have not added methods for removing binding yet, but what do you think about usability of current class using KeyPath? any obvious problem with this class?









      share









      New contributor




      Afshin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      I recently started Swift and iOS development. After checking this cool tutorial for writing a small library for 2-way binding between views and data model, I decided to improve and simplify binding part. So I wrote a small observer/binder classes (based on idea on mentioned post, observer class is almost identical) to simplify binding. It works as expected, but since I'm new to iOS and Swift, I want someone to check if there is any crucial problems with my binding class. Here are classes:



      class Observable<Object> {
      typealias ObservableDelegate = (Object)->Void

      var value: Object? {
      didSet {
      if let value = value {
      notify(newValue: value)
      }
      }
      }

      private var observers = [ObservableDelegate]()

      public init(_ value: Object? = nil) {
      self.value = value
      }

      func addObserver(_ delegate: @escaping ObservableDelegate) {
      observers.append(delegate)
      }

      private func notify(newValue value: Object) {
      for delegate in observers {
      delegate(value)
      }
      }
      }

      class ViewBindings {
      private class BindingEventHandler: NSObject {
      typealias BindingEventHandlerDelegate = () -> Void

      let target: BindingEventHandlerDelegate

      init(_ delegate: @escaping BindingEventHandlerDelegate) {
      target = delegate
      super.init()
      }

      @IBAction func valueChanged() {
      self.target()
      }
      }

      private var bindings = [BindingEventHandler]()

      func bind<KeyRoot,Value>(_ obj: NSObject, from: ReferenceWritableKeyPath<KeyRoot,Value>, to: Observable<Value>) where Value: Equatable {
      observeBind(obj, from: from, to: to)

      if let control = obj as? UIControl {
      let handler = BindingEventHandler {
      [weak obj, weak to] in
      if let _to = to {
      if let val = (obj as? KeyRoot)?[keyPath: from], _to.value != val {
      _to.value = val
      }
      }
      }

      bindings.append(handler)
      control.addTarget(handler, action: #selector(BindingEventHandler.valueChanged), for: [.editingChanged, .valueChanged])
      }
      }

      func observeBind<KeyRoot,Value>(_ obj: NSObject, from: ReferenceWritableKeyPath<KeyRoot,Value>, to: Observable<Value>) where Value: Equatable {
      to.addObserver {
      value in
      DispatchQueue.main.async {
      [weak obj] in
      (obj as? KeyRoot)?[keyPath: from] = value
      }
      }
      }
      }


      And here is a simple use of my ViewBindings class:



      class ViewController: UIViewController {
      @IBOutlet weak var textfield: UITextField!
      @IBOutlet weak var label: UILabel!

      let v1 = Observable<String?>()
      let binds = ViewBindings()

      override func viewDidLoad() {
      super.viewDidLoad()

      binds.bind(textfield, from: UITextField.text, to: v1)
      binds.bind(label, from: UILabel.text, to: v1)
      }

      @IBAction func btnpressed(_ sender: Any) {
      v1.value = "hello"
      }
      }


      Improvements in comparison with original post




      1. In original implementation, you needed to extend control classes to conform to Bindable protocol, but it is not needed here.

      2. You can add multiple bindings for 1 control easily here (currently bind one time and observeBind multiple times.


      I have not added methods for removing binding yet, but what do you think about usability of current class using KeyPath? any obvious problem with this class?







      swift ios





      share









      New contributor




      Afshin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.










      share









      New contributor




      Afshin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      share



      share








      edited 38 secs ago





















      New contributor




      Afshin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 6 mins ago









      Afshin

      1011




      1011




      New contributor




      Afshin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Afshin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Afshin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.



























          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });






          Afshin is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210684%2fsmall-2-way-binding-for-swift%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          Afshin is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          Afshin is a new contributor. Be nice, and check out our Code of Conduct.













          Afshin is a new contributor. Be nice, and check out our Code of Conduct.












          Afshin is a new contributor. Be nice, and check out our Code of Conduct.
















          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210684%2fsmall-2-way-binding-for-swift%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Morgemoulin

          Scott Moir

          Souastre