<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Omar Radwan on Medium]]></title>
        <description><![CDATA[Stories by Omar Radwan on Medium]]></description>
        <link>https://medium.com/@oradwan037?source=rss-11cdb8407668------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*huZhJSyjs5jdBybcevS0RQ.jpeg</url>
            <title>Stories by Omar Radwan on Medium</title>
            <link>https://medium.com/@oradwan037?source=rss-11cdb8407668------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 16:35:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oradwan037/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Swift Intensely (Part 2)]]></title>
            <link>https://medium.com/@oradwan037/swift-intensely-part-2-e191399e8cff?source=rss-11cdb8407668------2</link>
            <guid isPermaLink="false">https://medium.com/p/e191399e8cff</guid>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[memory-improvement]]></category>
            <category><![CDATA[swift-performance]]></category>
            <dc:creator><![CDATA[Omar Radwan]]></dc:creator>
            <pubDate>Mon, 15 Apr 2024 08:45:37 GMT</pubDate>
            <atom:updated>2024-04-15T08:47:26.703Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s learn how Swift works internally and how to manage its performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ck_C_Bszl_Uspx_5GQfn9A.jpeg" /><figcaption>Swift Performance ||</figcaption></figure><p>Hello, welcome back again 🥰. In <a href="https://medium.com/@oradwan037/swift-intensely-part-1-07d0c047f6e3"><strong>Part 1</strong></a> we discussed a lot of interesting things like <strong>Memory allocation</strong>, <strong>Reference counting</strong>, and <strong>Method dispatch</strong> and learned how Swift manages its memory behind the scenes. I suggest going and reading it first before reading this part.</p><p>This part will talk about <strong>Protocol Types</strong> and <strong>Generics</strong> in a different way than you already know. So, Let’s get started.</p><h3><strong>Protocol Types</strong></h3><p>How can we go to writing a polymorphism code with structs?<br>Answer: <strong>Protocol Oriented Programming (POP)</strong></p><p>With protocol types, we will look at how variables of protocol types are stored and copied and how method dispatch works. Let’s go back to the main example we have in the previous part but this time we will use protocol types and structs.</p><pre>// Polymorphism without inhertance<br><br>protocol Drawable { func draw() }<br><br>struct Point: Drawable {<br>    var x,y: Double<br>    func draw() {...}<br>}<br><br>struct Line: Drawable {<br>    var x1,x2,y1,y2: Double<br>    func draw() {...}<br>}<br><br>var drawables: [Drawable]<br>for d in drawables {<br>    d.draw()<br>}</pre><p>Our program is now still polymorphic and each struct is conformed to <strong>Drawable</strong> will draw its implementation. But, there is one different thing compared to the last example in part 1.<br>Now we have value types and they don’t have a common inheritance relationship or reference in memory which is important to create the V-Table dispatch mechanism that reference types use.</p><p><strong>So, How does Swift dispatch to the correct method?!<br></strong>Answer:<strong> Protocol Witness Table (PWT)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o2OsssmRurQM6KVCUXpkfg.png" /><figcaption><strong>Protocol Witness Table (PWT)</strong></figcaption></figure><p>The table-based mechanism <strong>PWT </strong>is the table Swift creates for each protocol and what conforms to this protocol to find the correct implementation for each one by linking it. Now we have to know how to find the method but actually, we still have two questions 😕.<br><strong>1- How do we get from the element into that array to that table? or How does the function know the location of this implementation in that Table?<br>2- How we will store our different sizes at the fixed offset of the array? (Line has 4 words and Point has 2 words)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1O6HU0T0v0Xe8552L4MoWA.png" /></figure><p>Swift uses a special storage layout called <strong>The Existential Container</strong>.</p><blockquote>In Swift, the term “The existential container” refers to the runtime representation of a value of a protocol type and Swift create it in the <strong>stack</strong>.</blockquote><blockquote>When you have a protocol type, Swift needs to store not only the value itself but also information about the type that conforms to the protocol. This information includes things like the type’s methods, properties, and associated types. The existential container is a runtime structure that holds both the value of the conforming type and the necessary type metadata.</blockquote><blockquote>The existential container allows you to work with values of protocol types in a type-erased manner, meaning you can interact with values without knowing the concrete types that conform to the protocol. This is commonly used in scenarios where you need to work with collections of values of different types that conform to the same protocol.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zLJeZ19l7Y3qHl8i0zpwSg.png" /></figure><p>The existential container contains five rows. The first three rows or words are reserved for the value buffer. Small types like our point (x,y) fit into our value buffer in the first two words. Okay but wait a second! What about our line which contains four words? The answer is Swift allocates memory on the heap and takes a pointer to this memory.</p><blockquote>The size of the value buffer within an existential container is not fixed at 3 words. It can vary depending on the size and alignment requirements of the concrete type being stored.</blockquote><blockquote>In Swift, the compiler dynamically allocates memory for the value buffer based on the requirements of the concrete type. If the concrete type fits within the value buffer (which typically includes a few words of memory), it is stored directly within the buffer. However, if the concrete type requires more space than the value buffer can hold, Swift allocates additional memory on the heap and stores a reference to it in the value buffer.</blockquote><blockquote>So, while the value buffer may be a few words in size for smaller types, it can expand dynamically to accommodate larger types or heap-allocated storage.</blockquote><p>Now let’s ask another question. <strong>What about the last two words in the existential container? and how Swift manages the difference between point and line.</strong></p><p>The answer is by our pointers to tables the first is the <strong>Protocol Witness Table (PWT)</strong> we talked about above and the new one is the table-based mechanism called the <strong>Value Witness Table (VWT). </strong>Let’s take a look ☺️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*9-QePKKq6YSAcZdBjnC9Rg.png" /><figcaption><strong>Value Witness Table</strong></figcaption></figure><p>The Value Witness Table manages the lifetime of our value and there is one type of table per type in our program. The VWT contains four types of functions (Operations).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dxBfo70bNhaVQ58RrS2Q3g.png" /></figure><p><strong>allocate:</strong> this function will allocate memory on the stack or allocate on the heap and store a pointer inside the value buffer of the existential container that is allocated in the stack.<br><strong>copy:</strong> Swift needs to copy the value from the source of the assignment that initializes our local variable into the existential container.<br><strong>destruct:</strong> decrement any reference counts for values that might be contained in our type.<br><strong>deallocate: </strong>deallocate the memory allocated in the heap for the value.</p><p>So, We have seen the mechanics of how Swift manages values of protocol type. Let’s see it in actual code step by step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*eUP2ybZoCjP3vsBN9IpsYg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*ujgv_BnA6VwEQYdcbgC0Fw.jpeg" /></figure><pre>struct Line: Drawable {<br>    var x1,x2,y1,y2: Double<br>    func draw() {...}<br>}<br><br>func drawACopy(local: Drawable) { // 3 copy<br>    local.draw() // 4 (PWT)<br>} // 5 -&gt; deallocate<br>let line: Drawable = Line(x1: 0.0, x2: 0.0, y1: 0.0, y2: 3.0) // 1<br>drawACopy(local: line) // 2 allocate<br><br>-------------------------------------------<br>// Pseudo code<br>// Generated code by compiler<br><br>struct ExistContainerDrawable {<br>    var valueBuffer: (Int, Int, Int)<br>    var vwt: ValueWitnessTable<br>    var pwt: DrawableProtocolWitnessTable<br>}<br><br>func drawACopy(val: ExitContDrawable) {<br>    var local = ExistContainerDrawable()<br>    let vwt = val.vwt<br>    let pwt = val.pwt<br>    local.pwt = pwt<br>    vwt.allocateBufferAndCopyValue(&amp;local, val)<br>    // projectBuffer get the address of the existential container<br>    pwt.draw(vwt.projectBuffer(&amp;local))<br>}</pre><p>Simply, The swift code example above explains what happened in the pics. First, Swift initializes the local existential container in the stack when we create a line and pass it to the drawACopy function. Then, the Value Witness Table allocates a place for a line in memory (in heap to our <strong>line</strong> case) and copies the values x1,y1,x2, and y2 to put them in the memory. After that, it will call the <strong>PWT </strong>to call the <strong>draw()</strong> method. At last, Swift uses <strong>VWT-deallocate </strong>to deallocate the instance from memory (stack&amp;heap).</p><p><strong>Summary of Protocol Types <br></strong>we saw how dynamic polymorphism works with value types throw protocol types and indirection through Witness Tables and Existential container.</p><h3>Generics</h3><p>In this last part, We will see generics but from another POV. I will look at how variables of generic type are stored and copied and how method dispatch works for them.</p><p>Generic code supports a more static form of polymorphism which is known as parametric polymorphism (One type per call context) and it supports a little bit more better performance.</p><pre>protocol Drawable {<br>    func draw()<br>}<br><br>struct Point: Drawable {<br>    var x1,x2: Double<br>    func draw() {...}<br>}<br><br>func foo&lt;T: Drawable&gt;(local: T) { <br>    bar(local)<br>} <br><br>func bar&lt;T: Drawable&gt;(local: T) {....}<br><br>let point = Point(x1: 0.0, x2: 0.0)<br>foo(local: point)</pre><p>We have a function <strong>foo</strong> which takes a generic parameter T constraint to <strong>Drawable </strong>and it passes this parameter to function<strong> bar </strong>which also takes<strong> </strong>generic parameter T<strong>. </strong>When function <strong>foo(local: point)</strong> executes, Swift will bind the generic type T to the type used at this call side (Point) -&gt; <strong>foo&lt;T = Point&gt;(local: point). </strong>So, The type substituted down the call chain -&gt; <strong>bar&lt;T = Point&gt;(local: point).<br></strong>This is what we mean by a more static form of polymorphism.</p><p>Let’s take a look at how Swift implements this under the hood.</p><p>In Swift, there are two types of terms for generics. the terms <strong>“Specialization”</strong> and <strong>“Unspecialization”</strong> are often used in the context of generics and performance optimization.</p><p><strong>Specialization:</strong> When a generic function or type is specialized, it means that the compiler generates separate implementations of that function or type for each concrete type it’s used with. This process allows the compiler to optimize the generated code specifically for each type, potentially improving performance by removing the overhead of dealing with generics at runtime. Specialization can result in more efficient code execution because the compiler can make assumptions about the concrete types involved.</p><pre>// Define a generic function that adds two values of any type<br>func add&lt;T&gt;(_ a: T, _ b: T) -&gt; T where T: Numeric {<br>    return a + b<br>}<br><br>// Call the generic function with two integers<br>let resultInt = add(5, 3)<br>print(&quot;Result (Int): \(resultInt)&quot;)<br><br>// Call the generic function with two floating-point numbers<br>let resultDouble = add(3.5, 2.5)<br>print(&quot;Result (Double): \(resultDouble)&quot;)</pre><p>In this example, the add function is generic and can work with any type that conforms to the Numeric protocol. When you call the function with Int arguments, the compiler generates a specialized version of the add function specifically for Int, optimizing the addition operation for integers. Similarly, when you call the function with Double arguments, the compiler generates another specialized version optimized for Double. These specialized versions improve performance by removing the overhead of generics and allowing the compiler to make assumptions about the concrete types involved.</p><blockquote>Swift compiler creates type-specific version of method and this kind to be really fast code. Swift will create a version per type use at the call site and it will look like that at compile time :-</blockquote><pre>func add(_ a: Int, _ b: Int) -&gt; Int{<br>    return a + b<br>}<br><br>func add(_ a: Double, _ b: Double) -&gt; Double{<br>    return a + b<br>}<br><br>let resultInt = add(5, 3)<br>let resultDouble = add(3.5, 2.5)</pre><p>Okay, that&#39;s really awesome no dynamic dispatch again everything is static, and Swift will create for each call a new static function at compile time and the code becomes really fast with <strong>Specialization</strong>.<br>But wait a second! <strong>Is this a potential to increase code size by a lot right?!</strong></p><p>Actually, the answer is <strong>No</strong> :D. Because the static typing information that is now available enables aggressive compiler optimization. Swift can reduce the code size here.</p><pre>// func add(_ a: Int, _ b: Int) -&gt; Int{<br>//    return a + b<br>// }<br><br>// func add(_ a: Double, _ b: Double) -&gt; Double{<br>//    return a + b<br>// }<br><br>let resultInt = 5 + 3<br>let resultDouble = 3.5 + 2.5</pre><p><strong>Unspecialization:</strong> Unsplization refers to the process of reverting from specialized code back to more general, generic code. This might occur in scenarios where the compiler determines that specialization is no longer necessary or beneficial. For example, if a specialized function is used with a wide variety of types, the compiler might choose to unspecialize it to reduce code size or improve compilation times.</p><pre>// Define a generic function that prints the description of a value<br>func printDescription&lt;T&gt;(_ value: T) {<br>    print(&quot;Description: \(value)&quot;)<br>}<br><br>// Call the generic function with different types<br>printDescription(42)       // Int<br>printDescription(&quot;Hello&quot;)  // String</pre><p>In this example, the printDescription function is generic and can be called with values of any type. When you call the function with different types (e.g., Int and String), the compiler generates specialized versions of the function for each type. However, if the function is used with a wide variety of types or if the optimization benefits are limited, the compiler might choose to unspecialize the function to reduce code size or improve compilation times.</p><p>These examples demonstrate how specialization and unspecialization work in Swift’s generics system, optimizing code performance and compilation efficiency based on the usage context.</p><p><strong>In summary,</strong> specialization involves generating optimized code tailored to specific types, while unspecialization involves reverting to more generic code when optimization is not needed or when it’s more efficient to do so. These concepts are important for understanding how Swift’s generics system works and how it impacts the performance of your code.</p><h3>Conclusion</h3><p>Always choose a fitting abstraction with the best dynamic runtime type requirements.</p><ul><li>struct types: Value semantics</li><li>class types: Identity &amp; OOP style polymorphism</li><li>Generics: Static polymorphism <strong>(Homogeneous)</strong></li><li>Protocol types: Dynamic polymorphism <strong>(Heterogeneous)</strong></li></ul><p>I hope you enjoyed this article and if you have a question you can ask me anytime on my <a href="https://www.linkedin.com/in/omarradwan1/"><strong>LinkedIn</strong></a>.</p><p>Thanks a lot ❤️👋🏻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e191399e8cff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Intensely (Part 1)]]></title>
            <link>https://medium.com/@oradwan037/swift-intensely-part-1-07d0c047f6e3?source=rss-11cdb8407668------2</link>
            <guid isPermaLink="false">https://medium.com/p/07d0c047f6e3</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift-performance]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[memory-improvement]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Omar Radwan]]></dc:creator>
            <pubDate>Mon, 15 Apr 2024 08:44:01 GMT</pubDate>
            <atom:updated>2024-04-15T08:46:17.509Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s learn how Swift works internally and how to manage its performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ck_C_Bszl_Uspx_5GQfn9A.jpeg" /><figcaption>Swift Performance</figcaption></figure><p>As iOS developers, Swift offers us aboard and powerful design space to explore. Swift has fantastic features with various mechanisms for code reusability and dynamism. With Swift, you have <strong>Struct, Class, Enum, Inheritance, Generics, and Protocols</strong>. Swift has different abstraction mechanisms to make a powerful app with design space, <strong>Modeling -&gt; </strong>How to use protocol-oriented programming to model your app and <strong>Performance </strong>which will focus on this article.<br>Now let’s begin by identifying the different dimensions to achieve the best performance to clean up and speed up some swift code.</p><ul><li><strong>Memory Allocation</strong></li><li><strong>Reference counting</strong></li><li><strong>Method dispatch</strong></li></ul><p>Also, We will gonna evaluate the performance of POP and look at some advanced swift features in Part 2.</p><ul><li><strong>Protocol types</strong></li><li><strong>Generics</strong></li></ul><p>So let’s get started. When you writing a program and want to choose your abstraction mechanism you need to ask yourself some questions. <br><strong>1-</strong> Is my instance gonna be allocated on the stack or heap?<br><strong>2- </strong>When I pass this instance around how much reference counting overhead am I going to incur?<br><strong>3-</strong> When I call a method on this instance, Is it going to be statically or dynamically dispatched?<br>If we want to write speed swift code we need to avoid paying for dynamism or runtime and heap allocation that we are not taking advantage of.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9_21rxUhg-dEb6WYvmF1OQ.png" /></figure><h3>Memory Allocation</h3><p>Swift automatically allocates and deallocates memory on your behalf. Some of that memory it allocates in the <strong>Stack. <br>A stack is a simple data structure, you can push at the end of the stack and you can pop off the end of the stack and we can implement the push and pop just by keeping the pointer to the end of the stack.</strong></p><p>When we want to call a function or create an instance we can allocate that in memory just by decrementing the stack pointer to make a space and when to deallocate we can increment the pointer again. That’s how fast stack allocation and deallocation are!!. It’s literally the cost of assigning an integer.</p><p>Also, Some of that memory it allocates in the <strong>Heap.<br>A heap is more complex than a stack. it’s more dynamic but less efficient than the stack. The heap can allocate memory with a dynamic lifetime but that requires a more advanced data structure.<br></strong>At heap allocation, you have to search for an unused block of memory with a suitable size, and at deallocation, it reinserts the block of memory back into the appropriate position.</p><p>We need to be careful when we deal with the heap that has a large cost like thread safety overhead and in this case, We have concurrency issues and can deal with it by locks or any other synchronization mechanisms.<br>Let’s take an example of Stack &amp; Heap allocation.</p><pre>// Stack allocation<br>// Struct<br><br>struct Point {<br>  var x,y: Double<br>  func draw() {}<br>}<br>let point1 = Point(x: 0, y: 0)<br>var point2 = point1<br>point2.x = 5<br></pre><p>When we create instance point1 and because Point is a struct, the x and y properties are stored in line in the stack. When assigning point1 to point2 we create a copy of that point and allocate it also in the stack. Now point1 and point2 are independent instances so when assigning value 5 to point2.x point1.x is still 0 and this is known as <strong>value semantics</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*C64UbqonVHRCP_udt3AjcA.png" /><figcaption>Instance allocation in the stack</figcaption></figure><p>Now we will use <strong>Class</strong> instead of <strong>Struct</strong> to let us know what has changed in memory.</p><pre>// Heap allocation<br>// Class<br><br>class Point {<br>  var x,y: Double<br>  func draw() {}<br>}<br>let point1 = Point(x: 0, y: 0)<br>var point2 = point1<br>point2.x = 5</pre><p>We are allocating memory in the stack but instead of the actual storage of the properties on point, we are going to allocate memory for references to point1 and point2. References to memory going to be allocated on the heap. So when we create an instance swift will look at the heap and search for that data structure for unused blocks of memory with its size and store the reference of it in the stack. Swift in heap allocation to our class point allocated four words of storage. In addition to the x and y words storage, we’re allocated two more words that Swift is gonna manage on our behalf (Blue boxes). After assigning point1 to point2 we are not gonna copy it but it will share the same data with different references and this is called <strong>Reference semantic</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*ZE1irAUucdeokvv-UL0WNA.png" /><figcaption>Instance allocation in the heap</figcaption></figure><p>Now we know why structs are cheaper than classes. classes require heap allocation and have reference semantics and because of that it has powerful characteristics like identity and indirect storage so if we don’t need this for our abstraction it will be better if we use a struct.</p><blockquote><strong>Hint:</strong> String in swift is a value type but actually in memory allocation it has the characteristics of references type and stores the contents of its characters indirectly on the heap.🤯</blockquote><h3>Reference Counting</h3><p>After talking about heap allocation, Now we need to know how Swift knows it’s safe to deallocate memory allocated in the heap. Swift just keeps a count of the total number of references to any instance in the heap. When you add a reference or remove a reference that reference count is incrementing or decrementing. When this count is zero swift knows that no one is pointing to this instance on the heap anymore and it’s safe to deallocate memory.</p><p>Like heap allocation, we must take the thread safety overhead into consideration because every reference can be added or removed to any heap instance on multiple threads at the same time which gonna make an unexpected behavior to our program so this cost can add up.</p><pre>// Heap allocation (Reference Counting)<br>// Class<br><br>class Point {<br>  var x,y: Double<br>  func draw() {}<br>}<br><br>let point1 = Point(x: 0, y: 0)<br>// retain is automatically increment our reference count<br>retain(point1)<br>var point2 = point1<br>//<br>retain(point2)<br>point2.x = 5<br>// release is automatically decrement our reference count<br>release(point1)<br>//<br>release(point2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*35kVI5J-q07pRvvXtaQWRQ.png" /><figcaption>Reference counting on Point class</figcaption></figure><p>When we create an instance point1 swift increment ref. count to 1 and when creating another instance point2 and assigning point1 to it we increment ref. count to 2 after the end of function swift will deallocate the instances and decrement the ref. count 1 by 1 to zero and boom it’s clean now ❤️👏🏻.</p><p>So, what about <strong>Structs</strong>?<br>When we constructed our point as a struct there was no heap allocation involved and when we copied it there was no heap allocation. So, there is no reference counting overhead.</p><p><strong>But, What if we have a more complicated struct that contains properties of type classes?</strong></p><pre>struct Label {<br>  var text: String<br>  var font: UIFont<br><br>  func draw() {} <br>}<br><br>let label1 = Label(text: &quot;Hello world&quot;, font: .fontSystem)<br>let label2 = label1</pre><p>Now our struct contains a text of type String and font of type UIFont. String as I mentioned above stores its content of characters on the heap so, that needs to be reference counted and font is a class so also needs to be reference counted. If we look at the memory representation:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*hQvryimUU12KV9Z-IPWREw.png" /><figcaption>Memory</figcaption></figure><p>label1 has two references one for <strong>text</strong> storage and one for <strong>font</strong> and when we copy it we will add two more references. <br>Swift tracks this process by retaining &amp; releasing algorithms as we talk about above.</p><blockquote><strong>Conclusion</strong> — Swift has to track lifetime for each instance (class) on the heap by reference counting and this is just one more reason to use structs.<br><strong>But,</strong> if struct contains references that will pay reference counting overhead as well. In fact struct will be pay reference counting overhead proportional to the number of references that they contain. if you have a struct that contains more than one reference they are retain more reference counting overhead than a class 😕. So, it will become bad idea if you use struct in this case.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*CxGABQOzJwzoXggNS4IMdw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*QGYEnpacRW0GC6bnPzqYoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*F4VxKb3tEjstfSX2Xzqpvw.png" /></figure><h3>Method Dispatch</h3><p>Now let’s move on to our final dimension of performance <strong>Method Dispatch.</strong></p><p>When you call a method at runtime, Swift needs to execute the correct implementation. If it can determine the implementation to execute at compile time, that’s known as <strong>Static Dispatch</strong>. At runtime, we are just going to be able to jump directly to the correct implementation. The compiler has visibility of the correct implementation so it’s able to optimize this code pretty aggressively including things like <a href="https://www.linkedin.com/pulse/optimizing-performance-inlining-rajiv-singh/"><strong>inlining</strong></a>.</p><p>This is in contrast to a <strong>Dynamic Dispatch. </strong>Dynamic dispatch isn’t going to determine a compile time directly which implementation to go to and look up implementation in the table at runtime and then jump to it.</p><blockquote><strong>Note:</strong> Dynamic dispatch is not that much more expensive than static dispatch. There’s just one level of indirection.</blockquote><p>But, this dynamic dispatch blocks the visibility of the compiler and so while the compiler can do all these cool optimizations for static dispatch, a dynamic dispatch, the compiler is not going to be able to reason through it.</p><pre>// Method Dispatch (Static)<br>// Struct (inlining)<br><br>struct Point {<br>  var x, y: Double<br>  func draw() {<br>    // Some implementation<br>  }<br>}<br><br>func drawAtPoint(_ point: Point) {<br>  point.draw()<br>}<br><br>let point = Point(x: 0, y: 0)<br>drawAtPoint(point)</pre><p>Well, in this example we have the draw method into our Point and drawAtPoint method which are both statically dispatched. What this means is the compiler knows exactly which implementation is going to be executed. That’s why static dispatch is <strong>Fast.</strong></p><p>So, Why and when do we have the dynamic dispatch thing at all?<br>Well, one of the reasons is it enables really powerful things like <strong>Inheritance-Based Polymorphism.</strong></p><p>Let’s look at the traditional Object-oriented programming code.</p><pre>/// Drawabale Abstract Class<br>class Drawabale { func draw() {} }<br><br>class Point: Drawabale {<br>  var x, y: Double<br>  override func draw() {...}<br>}<br><br>class Line: Drawabale {<br>  var x, y: Double<br>  override func draw() {...}<br>}<br><br>var drawables: [Drawabale]<br>for drawable in drawables {<br>  drawable.draw()<br>}</pre><p>Now we have a program that can polymorphically create an array of Drawabales and each one of them has its custom draw implementation and that’s when the dynamic dispatch comes into play. So, How this works? How does the compiler know the actual implementation for each one of this array of classes?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*Vorcr26oiDywDW6p6kuxeQ.jpeg" /></figure><p>Well, because Drawable, Line, and Point are all classes, We can create an array of these things and they all are the same size because we are storing them by reference in the array and then we go through each of them and call draw() to each of them. Now we know why the compiler can’t determine at compile time which is the correct implementation to execute. So, drawable.draw() could be a line or point or anything else. But still, we want to know how does it determine which one to call!?</p><p>Answer: <strong>Polymorphism Through V-Table Dispatch</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*CEJchpxkixFbvCgNcp5JGw.jpeg" /><figcaption><strong>V-Table Dispatch</strong></figcaption></figure><p>Well, The compiler adds another field to classes which is a pointer to the type information of that class, and stores it in static memory.</p><p>When we go to call draw, The compiler looks through the type to something called the <strong>Virtual Method Table</strong> on the type and static memory, which contains a pointer to the actual implementation to execute. After looking at the correct draw implementation in the V-Table by its type, it passes the actual instance as the implicit self-parameter.</p><pre>/// Compiler Execution<br><br>for drawable in drawables {<br>  // Compiler replace this &quot;drawable.draw()&quot; with this<br>  drawable.type.vTable.draw(drawable)<br>}</pre><p>Well, Classes by default are dynamically dispatched to their methods. This doesn’t make a big difference on its own, but when it comes to method chaining and other things, it can prevent optimizations.</p><blockquote><strong>Note:</strong> Not all classes are dynamically dispatched 🧐. When you mark your class with the <a href="https://gurjit-singh.medium.com/what-is-final-class-in-swift-53a0246f6abd#:~:text=In%20Swift%2C%20the%20final%20keyword,cannot%20be%20overridden%20or%20subclassed."><strong>final</strong></a> keyword, That means you never intend for a class to be subclassed. The compiler will pick up on this and it’s going to be statically dispatched its methods.</blockquote><p>Also plus its performance advantages, The <strong>final</strong> keyword has security importance check this amazing article for <strong>Dave Poirier. </strong><br><a href="https://blog.encoded.life/the-importance-of-final-for-security?source=more_articles_bottom_blogs">https://blog.encoded.life/the-importance-of-final-for-security?source=more_articles_bottom_blogs</a></p><h3>Conclusion</h3><p>What I want you to know from this part is these questions to ask yourself every time you gonna design a model or read or write a Swift code. <br><strong>Is this instance gonna be allocated in the stack or the heap?<br></strong> <strong>How much reference counting do I have when passing a reference around?</strong><br>when I call a method in an instance<strong>, Is it gonna be statically or dynamically dispatched?</strong><br>I think now you have a full understanding and deep dive into how the swift things work.<br>Every iOS developer needs to understand this not just only struct is a value type and class is a reference type without knowing what happening behind the scenes.</p><p>So, That&#39;s the end of <strong>Swift Intensely (Part 1) ❤️ .</strong></p><p>We will continue and wait for you in <a href="https://medium.com/@oradwan037/swift-intensely-part-2-e191399e8cff"><strong>Part 2</strong></a> to talk about more advanced topics in Swift like</p><ul><li><strong>Protocol types</strong></li><li><strong>Generics</strong></li></ul><p><strong><em>See you 👋🏻🍎</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07d0c047f6e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI Under The Hood]]></title>
            <link>https://medium.com/@oradwan037/swiftui-under-the-hood-ec5330d9d28c?source=rss-11cdb8407668------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec5330d9d28c</guid>
            <dc:creator><![CDATA[Omar Radwan]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 18:21:05 GMT</pubDate>
            <atom:updated>2023-07-27T12:49:30.060Z</atom:updated>
            <content:encoded><![CDATA[<h3>SwiftUI under the hood</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wWBu0nlvhbMopnW9BgFrug.jpeg" /></figure><p>Hello, welcome back with me again. Today our main talk is gonna be on SwiftUI, not gonna explain views or modifiers or animations but How SwiftUI works under the hood, and we will going to demystify it.</p><p>I suggest this article to everyone who wants to learn SwiftUI from scratch or also who had knowledge but needs to be deep in SwiftUI.</p><h4>SwiftUI as a framework</h4><p>We all know that SwiftUI is a declarative UI framework and a <strong>declarative</strong> framework is about <strong>what to do not how to do it</strong>. So That means that you describe what you want for your app at a high level, and SwiftUI decides exactly how to make it happen. That’s why SwiftUI is very easy, unlike imperative frameworks like UIKit. <strong>Imperative</strong> programming techniques, where we specify the steps that the program should take to achieve a particular result.</p><h4>SwiftUI behind the scene</h4><p>When you write your code in SwiftUI it translates to three types of behaviors:- <strong>Identity</strong>, <strong>Lifetime</strong>, and <strong>Dependencies</strong>.</p><h3>Identity</h3><p>Identity is how SwiftUI recognizes elements as the same or distinct across multiple updates of your app. Before we deep dive into identity look into this picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*7IgFdTEQ-dtoVzQaVJ4AKw.png" /><figcaption>Same or different cats?</figcaption></figure><p>Now if I ask you if you can tell me this one cat with two different positions or these two different cats? you can&#39;t tell me, right? That means the view can transition between states and changes (color — position — frame) but it’s still the same view or it can be more than one different view.</p><p>For now, let’s look at how identity is represented in your code, focusing on the two different types of identity used by SwiftUI.</p><p><strong>Explicit identity:</strong> using custom or data-driven identifiers. Assigning names or identifiers like this is a form of explicit identity and we need to keep track of all those unique names. So we need to know the name of the cat || the cats to know if they are the same or not (SwiftUI want not me 😁).</p><p>UIKit and AppKit use pointer identity which is one form of explicit identity but SwiftUI doesn’t because its value types use structs however UIKit &amp; AppKit uses classes and their reference type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qu3PM_IfByj8qeuL8nqP1A.png" /><figcaption>UIViews and NSViews are classes &amp; their memory pointers</figcaption></figure><p>Each UIView or NSView has a unique pointer to its memory allocation. We can refer to individual views just using their pointer, and if two views share the same pointer, we can guarantee that they are really the same view.</p><blockquote>Check this link to know why SwiftUI uses value types instead of classes for its view <a href="https://stackoverflow.com/questions/24232799/why-choose-struct-over-class#:~:text=Structs%20are%20preferable%20if%20they,or%20in%20a%20multithreaded%20environment."><strong>SwiftUI essentials</strong></a></blockquote><p>Now we will show an example of how SwiftUI uses this special identifier to improve performance and generate correct transitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d3rn-8B1hTII6Qf-rZPQag.png" /><figcaption>dogTagID — Exipilicit identifier | figure from Apple session “demystify SwiftUI”</figcaption></figure><p>if one dog from the rescue dogs section changes and go to adopted dogs SwiftUI will know by dogTagID to understand the changes and perform animation in the right way smoothly.</p><blockquote><strong>Note:</strong> Every view in SwiftUI has an identity even it’s expilicit or structural identity</blockquote><blockquote>— — — — — — — — — — — — — — —</blockquote><p><strong>Structural identity:</strong> distinguishing views by their type and position in the view hierarchy. The structural identity is how SwiftUI understands your view hierarchy without any specific identifiers. SwiftUI accomplishes this by looking at the type structure of your view hierarchy.</p><p>Now let’s see an example to demonstrate what is happening behind the scene on structural identity.</p><pre>struct ExampleView: View {<br>     let isLogged: Bool<br>     var body: some View {<br>          if isLogged {<br>              FeedView()<br>          } else {<br>              LoginView()<br>          }<br>     }<br>}<br><br>print(Mirror(reflecting: ExampleView(isLogged: false).body))<br>/* Translate to <br>    _ConditionalContent&lt;<br>          FeedView,<br>          LoginView<br>    &gt;<br>*/</pre><p>SwiftUI now translates our hierarchy to act as a tree and with if/else we have branches. SwiftUI translated the if/else to <strong>_ConditionalContent </strong>view, which is generic over its true and false content by the property wrapper <strong>@ViewBuilder</strong>.</p><p>The View protocol implicitly wraps its body property in a ViewBuilder, which constructs a single generic view from the logic statements in our property. This ViewBuilder is responsible for this translation, which is a type of result builder in Swift.</p><p>Learn more about @<strong>ViewBuilder </strong>in this<strong> </strong><a href="https://www.avanderlee.com/swiftui/viewbuilder/"><strong><em>article</em></strong></a></p><p>Now SwiftUI knows <strong>(In Runtime)</strong> that the true view is always FeedView and the false view is LoginView and if any change happens SwiftUI will destroy and deallocate the view state.</p><blockquote><strong>Note:</strong> rebuild the ExampleView again from scratch by a new state that happens by comparison with the previous state. SwiftUI see what is just changed and change it’s specific state fo that and that very important note to know</blockquote><p>Let’s see another Example to understand the Branching algorithm.</p><pre>struct ExampleView: View {<br>     let isEnabled: Bool<br>     var body: some View {<br>          if isEnabled {<br>              FeedView()<br>          } else {<br>              FeedView()<br>                  .disabled(true)<br>          }<br>     }<br>}</pre><p>In the current example, we still use the branching with if/else and SwiftUI destroys the view and creates another if isEnabled toggled. In this case, we lost our state for the instance of the FeedView state. The branching algorithm is good and powerful, especially in different views but if the view is the same there is another way recommended by Apple and more efficient in these cases like that.</p><pre>struct ExampleView: View {<br>     let isEnabled: Bool<br>     var body: some View {<br>              FeedView()<br>                  .disabled(isEnabled ? true : false)<br>     }<br>}</pre><p>That’s much better for performance and less for writing code. We inline the condition inside the view modifier which allow us to keep our state and our structural identity without any deallocations.</p><p>Now that we understand how SwiftUI identifies your views, let’s explore how identity ties into the lifetime of your views and data.</p><h3>Lifetime</h3><p>First, What is a lifetime of view or data?</p><p>Lifetime in SwiftUI is how SwiftUI tracks the existence of views and data over time. And This will help you better understand how SwiftUI works. Now let’s see what I mean in this example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1m5lkrQ7cSXl2_jy17QyTQ.png" /><figcaption>figure from Apple session “demystify SwiftUI” wwdc21</figcaption></figure><p>Now we see that our emoji/view is in different states with different values over time and moves through its lifetime. Identity allows us to define a stable element for different values and every single state is a different value for view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nq4ZIqI5_CB-NSdJgtxZbw.png" /></figure><p>We have PurrDecibelView a single view and take in his initializer an intensity that changes the state over time in the same view and when the value changes SwiftUI destroys the old state. SwiftUI will keep around a copy of the value to perform a comparison and know if the view has changed.</p><p>Once the identity of the view changes from onAppear() to Disappear or the view is removed, its lifetime ends.</p><blockquote>Note: A view’s lifetime is the duration of its identity in memory.</blockquote><p>To provide my model type with a stable notion of identity it should conform to <strong>Identifiable</strong> protocol to make keep track of lifetime efficiency.</p><pre>struct Emoji: Identifiable {<br>    var id: UUID()<br>    var shape: String<br>}</pre><blockquote>Important: your identity needs to be stable over a lifetime and non-changeable.</blockquote><h3>Dependencies</h3><p>how SwiftUI understands when your interface needs to be updated and why depends on something. A dependency is just an input injected into the view. When the dependencies change, the view is recomputed and generates a new hierarchy body.</p><pre>struct CatView: View {<br>    @Binding var cat: Cat // -&gt; Dependencies 1<br>    var food: Food  // -&gt; Dependencies 2<br><br>    var body: some View {  // -&gt; Body<br>        Button {<br>            cat.eat(food)  // -&gt; Action<br>        } Label: { <br>            Text(&quot;Eat&quot;) <br>          }<br>    }<br>}</pre><p>At our first look at the view, we see that dependency 1,2 is just input to the view. But when a dependency changes, the view is required to produce a new body (Hirariechy of our view). inside our body, we can see the <strong>Button</strong> with action. Actions are the trigger that changes the view’s dependencies. and let’s see how.</p><blockquote>We have [<strong>Cat and Food] </strong>injected<strong> -&gt; [CatView] </strong>that contain<strong> -&gt; [Button] </strong>with gesture make<strong> -&gt; [Action] -&gt; </strong>Changes the cat after eating and if he want more we gonna to go again to first<strong> ~ [Cat and Food] </strong>injected<strong> -&gt; [CatView] </strong>that contain<strong> -&gt; [Button] </strong>with gesture make<strong> -&gt; [Action]…..</strong></blockquote><p>When the dependencies changes, The body is recomputed and generates a new one. Check this to understand more about D<a href="https://developer.apple.com/wwdc20/10040">ata flow in SwiftUI</a>.</p><p>In SwiftUI, each view can have its own set of dependencies. So far, this still looks like a tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MYj11KND47I6ylb8sGfkaA.png" /><figcaption>Dependency tree</figcaption></figure><p>there can be multiple views dependent on the same state or other data. For example, one of the descendants might depend on the cat, too. And this could happen for one of our other dependencies. So we started with a tree, but this structure only loosely resembles a tree now.</p><p>In fact, if we rearrange it to avoid overlapping lines, we end up with this structure, which reveals that this is actually a graph, not a tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GuLG3zj61qdDnlgkbQ-UcA.png" /><figcaption>We call this structure the “Dependency graph”.</figcaption></figure><p>This structure is important because it allows SwiftUI to efficiently update only those views that require a new body.</p><p>The secret of the graph is that if the dependency changes, only those views will be invalidated. SwiftUI will call each view’s body, producing a new body value for each view. SwiftUI will instantiate the values of each invalidated view’s body.</p><p>That may result in more dependencies changing, but not always! Because views are value types, SwiftUI can efficiently compare them to only update the right subset of views.</p><p>A view’s value is short-lived. The struct value is just used for comparison, but the view itself has a longer lifetime.</p><p>And that’s how we can avoid generating a new body for the view in the center.</p><p>An identity is the backbone of the dependency graph.</p><h3>Conclusion</h3><p>SwiftUI is amazing and simpler than UIKit in many things but you need to understand carefully what are you typing and type it in the right way to achieve the best performance. If you understand carefully these three concepts you will write “<strong>Better apps with less code</strong>“ 😁🍎 in a perfect way.</p><h3>Resources</h3><ul><li><a href="https://developer.apple.com/wwdc21/10022">https://developer.apple.com/wwdc21/10022</a></li><li><a href="https://developer.apple.com/wwdc23/10160">https://developer.apple.com/wwdc23/10160</a></li></ul><p>I hope you enjoyed this article and if you have a question you can ask me anytime on my <a href="https://www.linkedin.com/in/omarradwan1/"><strong>LinkedIn</strong></a><strong> </strong>or you can see Apple videos and I confirm that you’ll understand deep dive better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec5330d9d28c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of UICollectionView Compositional Layout | Swift | UIKit]]></title>
            <link>https://medium.com/@oradwan037/the-power-of-uicollectionview-compositional-layout-swift-uikit-ec2d817eb15c?source=rss-11cdb8407668------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec2d817eb15c</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[Omar Radwan]]></dc:creator>
            <pubDate>Wed, 06 Jul 2022 06:03:24 GMT</pubDate>
            <atom:updated>2022-07-06T06:51:06.030Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A Guide To Build Complex Layout</blockquote><blockquote><em>Hello, welcome to my article. We all know that if we have a complex design and repeatable sections the first thing that comes to our minds is</em> <strong><em>UICollectionView.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O1D1-dnF4i87xfJJXpPVZQ.png" /></figure><p><a href="https://developer.apple.com/videos/play/wwdc2019/215/">At <strong>WWDC19</strong></a>, Apple introduces a powerful and unbelievable API for building complex layouts. <a href="https://developer.apple.com/documentation/uikit/uicollectionviewcompositionallayout"><strong>UICollectionViewCompostionalLayout</strong></a> was made to simplify the collection view layouts using a declarative way without the need for nested collection views to achieve customization.</p><h3>Overview of Basic UICollectionView</h3><p>We will not talk too much about the UICollectionView layout because most of us know everything about it and if not you can check this <a href="https://developer.apple.com/documentation/uikit/uicollectionview"><strong>link</strong></a> then, you can back and continue learning UICollectionView Compositional Layout. In CollectionView we can control the size of our cells and achieve simple layouts by using <strong>UICollectionViewFlowLayout</strong> &amp; <strong>UICollectionViewLayout</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*7EPzMlWFSB-iAglSIKHxZw.png" /><figcaption>UICollectionViewFlowLayout</figcaption></figure><p>let&#39;s see this example If we need to achieve this design of the App Store page, we will face complexity in our code and our brain get mad.</p><p>There is a Collection view that represents a Collection view cell inside the biggest Collection view in one section!!. That’s absolutely so hard for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Pp5uyYXw3wyvALdy7NfKQ.png" /></figure><h3>Intro to UICollectionView Compositional Layout</h3><p>Now, in Compositional layout Forget everything you know about collection view layouts! yes, that’s it. But we will think a bit differently about traditional section- and item-based layouts. In our flow layout, a section was comprised of multiple items, laid out in horizontal lines that were stacked vertically.</p><p><strong>UICollectionCompositionalLayout</strong> introduces a new layer between the section layer and item layer and its Group and I’ll make you understand what I mean. CollectionView layout is comprised of sections, sections are comprised of groups, and groups are comprised of items and optionally other groups. Let’s Take a look at how our layout structure can be modified to incorporate groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*J82v0f1FQslmGOkOFUGG-w.png" /><figcaption><em>A compositional layout with items nested in groups </em>vertically<em> within a section.</em></figcaption></figure><p>And there is another picture that shows how Compositional layout work (App Store) Ex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*8uC9ID3iI303I9EOFtLDtg.png" /><figcaption><em>A compositional layout with items nested in groups </em>horizontally<em> within two sections.</em></figcaption></figure><p>Sections and items described in a compositional layout correspond 1-to-1 with the sections and items of our collection view data source. Groups, however, don’t have a data source equivalent, nor do they render content like items/cells. They’re used solely to describe the layout of our items within a section.</p><p>In the diagram above, each group represents a horizontal line of our layout. We’ll get fancier in a bit, but for now, we’ll structure our first compositional layout in this manner. Speaking of our first compositional layout, let’s get started on that now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*pfUq2MpoB4mAbom1e-9j8A.gif" /><figcaption>Our Example</figcaption></figure><p>This is the project we will create and I promise you’ll learn a lot from it. You can find the project <a href="https://github.com/oradwanomar/Sway"><strong>here</strong></a>. We will not touch everything in the project like (Cell design and header view…etc) but we will focus on how to make this layout. Now we will speak to our first compositional layout so let’s get started.</p><h3>UICompositional Layout in coding</h3><p>Before everything, we will set up our <strong>Layout</strong> and then set this layout to our CollectionViewLayout.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7f9eb485735e54befce83e6ba896e09/href">https://medium.com/media/a7f9eb485735e54befce83e6ba896e09/href</a></iframe><p>we create a layout from the UICollectionViewCompositionalLayout type that gives us the section index and now we can create in each section our custom layout that will return a NSCollectionLayoutSection.</p><p>Note that NSCollectionLayoutSection simply describes the layout of any section in the layout we’re creating. We’re not adding any data to the collection view here. Let’s make it cleaner and create a function that returns a NSCollectionLayoutSection and then, calls this function in our Switch-Case above.</p><pre><strong>func</strong> foodBannerSection()-&gt; NSCollectionLayoutSection {</pre><pre>     let section = NSCollectionLayoutSection(group: <strong><em>group</em></strong>)</pre><pre>     return section<br>}</pre><p>Okay, but we need to declare that <strong><em>group</em></strong>. That’s right… because a layout is comprised of sections, which are comprised of groups, which are comprised of groups and items. Let’s work backward from here.</p><p>A group is represented by a <a href="https://developer.apple.com/documentation/uikit/nscollectionlayoutgroup">NSCollectionLayoutGroup</a>. To create one, we need to describe its size relative to its containing section, specify whether we want it to lay items out horizontally or vertically, and describe the items it will contain. In our case now We’ll use the class function <a href="https://developer.apple.com/documentation/uikit/nscollectionlayoutgroup/3213855-horizontal">NSCollectionLayoutGroup.horizontal(layoutSize:subitems:)</a> to do this since we want our group to lay out its items horizontally, but first, we need to understand the sizing of our group and our items.</p><p>Sizing is describing groups and items in relation to their respective container size or to their super container size. More specifically, the size of a group can be described relative to its containing group or section’s size, and the size of an item can be described relative to its containing group’s size. We can describe our size to group or item by NSCollectionLayoutSize</p><pre><strong>let</strong> groupSize = NSCollectionLayoutSize(widthDimension: , heightDimension: )</pre><pre><strong>let</strong> group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: <strong>[<em>item</em>]</strong>)</pre><p>Now, What are the width and height dimensions for our group?. You can express a group’s or item’s dimensions using an <strong>absolute</strong>, <strong>estimated</strong>, or <strong>fractional value</strong>.</p><p>Use an <strong><em>absolute value</em></strong> to specify exact dimensions, like a 44 x 44 point square:</p><pre>let absoluteSize = NSCollectionLayoutSize(widthDimension: .absolute(44),                                         heightDimension: .absolute(44))</pre><p>Use an <strong><em>estimated value</em></strong> if the size of your content might change at runtime, such as when data is loaded or in response to a change in system font size. You provide an initial estimated size and the system computes the actual value later.</p><pre>let estimatedSize = NSCollectionLayoutSize(widthDimension: .estimated(200),                                          heightDimension: .estimated(100))</pre><p>Use a <strong><em>fractional value</em></strong> to define a value that’s relative to a dimension of the item’s container. This option simplifies specifying aspect ratios. For example, the following item has a width and a height that are both equal to 50% of its container’s width, creating a square that grows and shrinks as the size of its container changes.</p><pre>let fractionalSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.5),                                           heightDimension: .fractionalWidth(0.5))</pre><p>Now that’s my dimensions for the first section. We don’t use .<strong>estimated</strong> here because I’m sure that my group will not be bigger at run time or something like that. Our group takes 70% of our section width and 255 for height, you can also make heightDimension: <strong>.fractionalHeight(0.8)</strong> that depends on your look.</p><pre><strong>func</strong> foodBannerSection()-&gt; NSCollectionLayoutSection {</pre><pre><strong>     let</strong> groupSize = NSCollectionLayoutSize(widthDimension:        .fractionalWidth(0.7), heightDimension: .absolute(225))</pre><pre><strong>     let</strong> group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: <strong><em>[item]</em></strong>)</pre><pre><strong>     let</strong> section = NSCollectionLayoutSection(group: group)</pre><pre>     return section<br>}</pre><p>We now need to define our layout’s items, which we used to create the NSCollectionLayoutGroup above. Items in the layout are represented by <a href="https://developer.apple.com/documentation/uikit/nscollectionlayoutitem">NSCollectionLayoutItem</a>, and just like groups, they are initialized with an NSCollectionLayoutSize. Now that we know how sizing works, this should be easy. Each item is filled by the group which it’s width is 70% of our section so, our item size will be taken 100% from his group size</p><pre><strong>func</strong> foodBannerSection()-&gt; NSCollectionLayoutSection {<br>     <strong>let</strong> itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1))</pre><pre><strong>     let</strong> item = NSCollectionLayoutItem(layoutSize: itemSize)</pre><pre><strong>     let</strong> groupSize = NSCollectionLayoutSize(widthDimension:        .fractionalWidth(0.7), heightDimension: .absolute(225))</pre><pre><strong>     let</strong> group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: <strong><em>[item]</em></strong>)</pre><pre><strong>     let</strong> section = NSCollectionLayoutSection(group: group)</pre><pre>     return section<br>}</pre><p>Now for the main event. The most amazing feature of compositional layouts.</p><h3>Orthogonal Scrolling</h3><p>We refer to this behavior as “orthogonal scrolling”. That is part of our layout scrolls along the opposite axis of the scrolling container. In this example, part of the layout scrolls horizontally in a vertically scrolling container.</p><p>How would you build this? I can’t tell you how many times I’ve nested horizontally scrolling flow-layout collection views inside of vertically scrolling table views. Scroll performance and view hierarchy architecture be damned!</p><p>What if I told you that you can achieve this behavior, allowing sections of your collection view to scroll horizontally within a vertically scrolling list without incurring a massive performance hit and with <strong>One Line Of Code</strong>.</p><pre>        section.orthogonalScrollingBehavior = .continuous<br>//or<br>        section.orthogonalScrollingBehavior = .groupPaging<br>//or<br>        section.orthogonalScrollingBehavior = .paging<br>//or<br>        section.orthogonalScrollingBehavior = .groupPagingCentered<br>//or<br>        section.orthogonalScrollingBehavior = .continuousGroupLeadingBoundary</pre><p>Now let’s add it to our function.</p><pre><strong>func</strong> foodBannerSection()-&gt; NSCollectionLayoutSection {<br>     <strong>let</strong> itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1))</pre><pre><strong>     let</strong> item = NSCollectionLayoutItem(layoutSize: itemSize)</pre><pre><strong>     let</strong> groupSize = NSCollectionLayoutSize(widthDimension:        .fractionalWidth(0.7), heightDimension: .absolute(225))</pre><pre><strong>     let</strong> group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: <strong><em>[item]</em></strong>)</pre><pre><strong>     let</strong> section = NSCollectionLayoutSection(group: group)<br>     section.orthogonalScrollingBehavior = .continuous</pre><pre>     return section<br>}</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fabf738b3892dfedec1078c21947ed5/href">https://medium.com/media/7fabf738b3892dfedec1078c21947ed5/href</a></iframe><p>And now let’s see what we have done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*89tm-_0p3GJyyfwYJIiOuA.gif" /></figure><p>That looks great but now I need to add some padding between groups and each other and also some padding to our leading, top, and bottom section. We can do it by NSDirectionalEdgeInsets .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b834083769669fc4175c1e3fa535a92b/href">https://medium.com/media/b834083769669fc4175c1e3fa535a92b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*-ujrOiJpQounZhUvYbzQHg.gif" /></figure><p>That’s pretty cool right :D</p><h3>Funny Bonus Animation</h3><p>Let’s play with some animation and scrollOffest by adding this to the section.</p><pre>section.visibleItemsInvalidationHandler = { (items, offset, environment) <strong>in</strong></pre><pre>     items.forEach { item <strong>in</strong></pre><pre><strong>     let</strong> distanceFromCenter = abs((item.frame.midX - offset.x) - environment.container.contentSize.width / 2.0)</pre><pre><strong>     let</strong> minScale: CGFloat = 0.8</pre><pre><strong>     let</strong> maxScale: CGFloat = 1.0</pre><pre><strong>     let</strong> scale = max(maxScale - (distanceFromCenter / environment.container.contentSize.width), minScale)</pre><pre>     item.transform = CGAffineTransform(scaleX: scale, y: scale)</pre><pre>     }</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*HMzSrLkHKralj20NpeGNww.gif" /></figure><p>Now you understand how every layout work and how to make your custom layout size so now, I will see you how I implement section 1and 2 in coding and I swear you will get everything and deal with it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9193d5e1625255fd31ce0431ce5ea778/href">https://medium.com/media/9193d5e1625255fd31ce0431ce5ea778/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16f500633d51dbfe526d5add0baf41fa/href">https://medium.com/media/16f500633d51dbfe526d5add0baf41fa/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3b85ab69a2ef602553b5545c113aa86/href">https://medium.com/media/b3b85ab69a2ef602553b5545c113aa86/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*pfUq2MpoB4mAbom1e-9j8A.gif" /></figure><h3>Supplementary Items</h3><p>We’ve accomplished a basic layout of our cells, but if you’ve worked with collection views before, you might know that your data source is also capable of vending reusable supplementary views to create things like headers, footers, and accessory views, and the like. So how do those fit into compositional layouts? Before we get there, I made a custom header and footer <strong>FilterHeaderView</strong> &amp; <strong>DividerFooterView.</strong></p><p>Make register to them first and let’s add a method to our data source to create a view we’d like to use as a header for the sections in our collection view.</p><pre>collectionView.register(FilterHeaderView.<strong>self</strong>,     forSupplementaryViewOfKind: &quot;Header&quot;, withReuseIdentifier: FilterHeaderView.headerIdentifier)</pre><pre>collectionView.register(DividerFooterView.<strong>self</strong>, forSupplementaryViewOfKind: &quot;Footer&quot;, withReuseIdentifier: DividerFooterView.footerIdentifier)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e09a523a95d0dc2113ba578345609c47/href">https://medium.com/media/e09a523a95d0dc2113ba578345609c47/href</a></iframe><p>And Then, add this to restaurantsListSection()</p><pre>section.boundarySupplementaryItems = [</pre><pre>.init(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(30)), elementKind: &quot;Header&quot;, alignment: .top),</pre><pre>.init(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(30)), elementKind: &quot;Footer&quot;, alignment: .bottom)</pre><pre>]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m6U9WVPI4UIV2Hr2YtJvKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_7YzUoRVnXWGyP0VIh-uqg.png" /><figcaption>Header &amp; Footer</figcaption></figure><h3>Decoration Items</h3><p>In addition to supplementary items, we can customize our section layout with decoration items. This will allow us to easily add backgrounds to our sections. The background view we’ll create is quite simple (a gray rectangle with a corner radius), so we’ll do it in code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd2b0e28521650e1ce9a9e27d194f1ca/href">https://medium.com/media/cd2b0e28521650e1ce9a9e27d194f1ca/href</a></iframe><pre>layout.register(SectionDecorationView.<strong>self</strong>, forDecorationViewOfKind: &quot;SectionBackground&quot;)</pre><p>In our layout declaration, we simply create a new decoration item for our background using <a href="https://developer.apple.com/documentation/uikit/nscollectionlayoutdecorationitem/3199051-background">NSCollectionLayoutDecorationItem.background(elementKind:)</a>, inset it a bit, and set it on our section.</p><pre><strong>let</strong> decorationItem = NSCollectionLayoutDecorationItem.background(elementKind: &quot;SectionBackground&quot;)</pre><pre>section.decorationItems = [decorationItem]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UrkSFeCkWzVzQ9JQL9zhLA.png" /></figure><h3>Conclusion</h3><p>We’ve come a long way since UICollectionView’s introduction in 2012. Apple and third-party developers have continued to push the envelope with increasingly complex layouts in their apps that look and work beautifully. UICollectionViewCompositionalLayout is an amazing, feature-packed API that addresses the needs of modern app developers.</p><h3>Source Code</h3><ul><li><a href="https://github.com/oradwanomar/Sway">https://github.com/oradwanomar/Sway</a></li><li>Fully Source code by an amazing man <a href="https://github.com/dheerajghub">dheerajghub</a> : <a href="https://github.com/dheerajghub/SwiggyClone">https://github.com/dheerajghub/SwiggyClone</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec2d817eb15c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>