<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Oleksandra Sildushkina</title>
    <description>The latest articles on DEV Community by Oleksandra Sildushkina (@sbotichelli).</description>
    <link>https://dev.to/sbotichelli</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F472192%2Fe1972466-50cc-42cf-a1ae-2c683983be6e.jpeg</url>
      <title>DEV Community: Oleksandra Sildushkina</title>
      <link>https://dev.to/sbotichelli</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/sbotichelli"/>
    <language>en</language>
    <item>
      <title>Binding data between classes with closures in Swift</title>
      <dc:creator>Oleksandra Sildushkina</dc:creator>
      <pubDate>Sun, 20 Sep 2020 10:47:38 +0000</pubDate>
      <link>https://dev.to/sbotichelli/binding-data-between-classes-with-closures-in-swift-1mfm</link>
      <guid>https://dev.to/sbotichelli/binding-data-between-classes-with-closures-in-swift-1mfm</guid>
      <description>&lt;p&gt;There are several ways of binding data between classes you can use in Swift.&lt;br&gt;
Let's start from the simple situation. We've got a parent and a child. If parent wan't to get child grades, it can just refer to them. But what if we've got a parent that wants to know a new mark as soon as child gets it?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Parent {
    var name: String
    var child: Child?

    init(_ name: String, child: Child? = nil) {
        self.name = name
        self.child = child
    }

    func getChildMarks() -&amp;gt; [Int]? {
        return child?.marks
    }
}

class Child {
    var name: String
    var marks: [Int]

    init(_ name: String, marks: [Int] = [], parent: Parent? = nil) {
        self.name = name
        self.marks = marks
    }
}

let child = Child("David", marks: [5, 5, 4])
let parent = Parent("Ms. Red", child: child)

print(parent.getChildMarks())
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;We should bind data. Let’s imagine, that our child is a responsible one and it has nothing against informing parents himself. But a child does not hold a reference to a parent object. So the most straightforward way is to give a child a reference to its parent. Let’s do that.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Child {
    var name: String
    var marks: [Int]
    weak var parent: Parent?

    init(_ name: String, marks: [Int] = [], parent: Parent? = nil) {
        self.name = name
        self.marks = marks
    }
}

let child = Child("David", marks: [5, 5, 4])
let parent = Parent("Ms. Red", child: child)
child.parent = parent
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now children holds a reference to a parent. Please pay attention that reference to a parent class should be weak. That will prevent a reference cycle if parent object will be deallocated. Now we can create a public method of a parent, which a child will call each time it gets a new mark.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    func childGotNewMark(_ mark: Int) {
        print("Child got \(mark).")
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;And each time a child gets a new mark, it adds it to the mark list and calls parents method to inform a parent.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    func getMark(_ mark: Int) {
        marks.append(mark)
        parent?.childGotNewMark(mark)
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This way has several disadvantages. What if we will attach a child to a parent that doesn’t have a childGotNewMark method? Obviously, we will get an error.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;error: value of type ‘Parent’ has no member ‘childGotNewMark’&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;What can we do to resolve this issue?&lt;br&gt;
The most common way is providing parent methods to a child as variables. Optional variables, so parent can either set them or not. So this child will be able to work with different parents. Let’s take a look at this solution. You can run this code in playground. Detailed explanations are going next.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Parent {
    var name: String
    var child: Child?

    init(_ name: String, child: Child? = nil) {
        self.name = name
        self.child = child
        guard let child = child else {
            return
        }
        child.onNewMarkReceived = { [weak self] mark in
            self?.childGotNewMark(mark)
        }
    }

    func getChildMarks() -&amp;gt; [Int]? {
        return child?.marks
    }

    func childGotNewMark(_ mark: Int) {
        print("Child got \(mark).")
    }
}

class Child {
    var name: String
    var marks: [Int]
    weak var parent: Parent?
    var onNewMarkReceived: ((Int) -&amp;gt; Void)?

    init(_ name: String, marks: [Int] = [], parent: Parent? = nil) {
        self.name = name
        self.marks = marks
    }

    func getMark(_ mark: Int) {
        marks.append(mark)
        onNewMarkReceived?(mark)
    }
}

let child = Child("David", marks: [5, 5, 4])
let parent = Parent("Ms. Red", child: child)
child.parent = parent

child.getMark(5)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;First we define a variable in child’s class.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;var onNewMarkReceived: ((Int) -&amp;gt; Void)?&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;What does that mean? We created a variable &lt;strong&gt;onNewMarkReceived&lt;/strong&gt; that is an optional method. It gets an &lt;strong&gt;integer&lt;/strong&gt; on input and returns &lt;strong&gt;void&lt;/strong&gt;.&lt;br&gt;
Next we will call this method when child gets it’s mark instead of &lt;code&gt;parent?.childGotNewMark(mark)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;onNewMarkReceived?(mark)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Question mark after the name ot the method means, that if the method in our variable is not defined, it will do nothing.&lt;br&gt;
On the next step we set the variable in parent’s initialisation code. It is a closure that takes mark (as an integer value) and doesn’t return anything.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;init(_ name: String, child: Child? = nil) {
        self.name = name
        self.child = child
        guard let child = child else {
            return
        }
        child.onNewMarkReceived = { mark in
            print("Child got \(mark)")
        }
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;But what if we want to pass this mark to some method of the parent instead of printing it? Let’s call &lt;code&gt;func childGotNewMark(_ mark: Int)&lt;/code&gt; we’ve created previously.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;child.onNewMarkReceived = { [weak self] mark in
            self?.childGotNewMark(mark)
        }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;What do we do here? First, we set our self as weak. That means that reference to a parent object is weak. So if parent object will be going to deallocate it’s memory, it will be able to do it, not worrying about the reference that closure holds to it.&lt;br&gt;
Next we refer to a method inside a parent. Self is required in a closure. Question mark after self is needed as at the moment when closure is called self can be already deallocated.&lt;br&gt;
So we’ve created a data binding from a child class to parent without using delegate pattern. It allows us to work with different parents, that might refrain of defining onNewMarkReceived method. It is also tolerant for the situations when parent is deallocated.&lt;/p&gt;

</description>
      <category>swift</category>
      <category>ios</category>
    </item>
  </channel>
</rss>
