<?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 Mustafa Özdemir on Medium]]></title>
        <description><![CDATA[Stories by Mustafa Özdemir on Medium]]></description>
        <link>https://medium.com/@mustiozdemir?source=rss-437c9692c8de------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xxUpCLU2zhGEFoSsAtvCwA.jpeg</url>
            <title>Stories by Mustafa Özdemir on Medium</title>
            <link>https://medium.com/@mustiozdemir?source=rss-437c9692c8de------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:41:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mustiozdemir/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[SwiftData]]></title>
            <link>https://medium.com/@mustiozdemir/swiftdata-71d42aa80a89?source=rss-437c9692c8de------2</link>
            <guid isPermaLink="false">https://medium.com/p/71d42aa80a89</guid>
            <category><![CDATA[swiftdata]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mustafa Özdemir]]></dc:creator>
            <pubDate>Fri, 10 Jan 2025 09:58:41 GMT</pubDate>
            <atom:updated>2025-01-10T09:58:41.731Z</atom:updated>
            <content:encoded><![CDATA[<h3>Merhaba SwiftData</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*_aof6eF7e8Jn3g0Yg82PYw.png" /><figcaption>SwiftData</figcaption></figure><p><em>iOS 17.0+ | iPadOS 17.0+ | Mac Catalyst 17.0+ | macOS 14.0+ | tvOS 17.0+ | visionOS 1.0+ | watchOS 10.0+</em></p><p><strong>Giriş</strong></p><p>iOS 17 ile birlikte Apple, veri yönetimi ve kalıcılığı (persistence) konusunda yepyeni bir yaklaşım sunan SwiftData framework’ünü tanıttı. Core Data’nın güçlü altyapısını modern bir yaklaşımla birleştiren SwiftData, geliştiricilere daha basit, daha anlaşılır ve Swift dilinin doğasına uygun bir çözüm sunuyor.</p><p>Bu yazıda, SwiftData’nın özelliklerini, avantajlarını, temel kullanım senaryolarını ve bir ToDoList uygulaması üzerinden örneklerle detaylı bir şekilde inceleyeceğiz. Eğer veri yönetimi ve kalıcılığı uygulamalarınızda kullanıyorsanız, SwiftData sizin için büyük bir fark yaratabilir.</p><p><strong>SwiftData Nedir?</strong></p><p>SwiftData, Core Data’nın modernleştirilmiş bir alternatifi olarak geliştirildi. Swift dilinin gelişmiş özelliklerinden, özellikle de Swift Macro’lardan faydalanarak geliştiricilere daha “Swifty” bir API sunuyor. SwiftData’nın amacı, veri modelleme ve veritabanı işlemlerini basitleştirmek, aynı zamanda performansı ve güvenilirliği artırmaktır.</p><p><strong>Neden SwiftData?</strong></p><p>Modern API: SwiftData, klasik Core Data API’sinin karmaşıklığını ortadan kaldırır ve daha sezgisel bir API sunar.</p><p>SwiftUI Entegrasyonu: SwiftData, SwiftUI ile mükemmel bir uyum içinde çalışır ve gerçek zamanlı UI güncellemelerini kolaylaştırır.</p><p>Swift Macros: @Model gibi makrolar, veri modellerini tanımlamayı ve yönetmeyi kolaylaştırır.</p><p>Core Data Tabanlı: SwiftData, Core Data’nın kanıtlanmış altyapısı üzerine inşa edilmiştir, bu nedenle güvenilir ve performanslıdır.</p><p>CloudKit Desteği: SwiftData, CloudKit ile entegrasyon sağlayarak veri senkronizasyonunu kolaylaştırır.</p><p><strong>SwiftData’nın Temel Kavramları</strong></p><p><strong>1. Modelleme</strong></p><p>SwiftData’da veri modelleri oluşturmak için @Model makrosu kullanılır. Bu makro, bir sınıfın SwiftData tarafından otomatik olarak veritabanı yönetim sistemiyle ilişkilendirilmesini sağlar.</p><p><strong>2. ModelContext</strong></p><p>SwiftData, ModelContext adı verilen bir nesneyle çalışır. Bu nesne, veri ekleme, güncelleme ve silme işlemleri gibi veritabanı işlemlerini gerçekleştirmek için kullanılır.</p><p><strong>3. İlişkiler</strong></p><p>SwiftData, veri modelleri arasında birden fazla ilişkiyi destekler:</p><p>Bire-bir (one-to-one) ilişkiler</p><p>Bire-çok (one-to-many) ilişkiler</p><p>Çoktan-çoğa (many-to-many) ilişkiler</p><p>Bu ilişkiler, veri modelinizin gereksinimlerine göre tanımlanabilir ve yönetilebilir.</p><p><strong>SwiftData ile Modelleme: Örnek Bir ToDoList uygulaması</strong></p><p>SwiftData’nın entegrasyon kolaylığını daha iyi anlamak adına bir ToDoList uygulaması örneğini inceleyelim.</p><p>Öncelikle ToDo listemize eklemek üzere kullanacağımız Taskların güncel durumunu belirten bir TaskStatus enum tanımlayalım. Yeni oluşturacağımız her Task new status’une sahip olarak başlar ve Task tamamlandığında status’u completed durumuna geçer.</p><pre>import Foundation<br><br>enum TaskStatus: String, Codable {<br>  case new = &quot;new&quot;<br>  case completed = &quot;completed&quot;<br>}</pre><p>Görev Modeli</p><p>Görev modelimiz @Model makrosu ile tanımlanır. Bu model, bir görevin başlık, açıklama, oluşturulma ve güncellenme tarihi gibi bilgilerini içerir:</p><pre>import Foundation<br>import SwiftData<br><br>@Model<br>class Task {<br>  var id: UUID<br>  var title: String<br>  var detail: String<br>  var status: TaskStatus<br>  var createdAt: Date<br>  var updatedAt: Date<br>  <br>  init(<br>    title: String,<br>    detail: String<br>  ) {<br>    self.id = UUID()<br>    self.title = title<br>    self.detail = detail<br>    self.status = .new<br>    self.createdAt = Date()<br>    self.updatedAt = Date()<br>  }<br>}</pre><p>Task isimli bir class oluşturduk. Uygulamamızdaki amaç kullanıcı Task tipinde yeni bir instance oluşturduğunda bunu kalıcı olarak saklamak isteyecektir. SwiftData kullanarak Task tipindeki instance’ları kayıt edebilmek için oluşturduğumuz bu Task modelinin @Model protocolüne conform etmesi gerekiyor.</p><p>Veritabanı İşlemleri</p><p><strong>1. ModelContext Kullanımı</strong></p><p>SwiftData ile çalışmak için bir ModelContext nesnesine ihtiyacınız var. Bu nesne, veritabanı işlemlerini gerçekleştirmek için bir bağlantı görevi görür ve çevresel bir değişken olarak tanımlanır:</p><pre>@Environment(\.modelContext) private var modelContext</pre><p><strong>2. Yeni Task Eklemek</strong></p><p>Yeni bir görev oluşturup veritabanına kaydetmek oldukça basittir:</p><pre>let task = Task(title: &quot;First Task&quot;, description: &quot;First Task Detail&quot;)<br>context.insert(task)</pre><p><strong>3. Task Durumunu Güncellemek</strong></p><p>Bir görevin durumunu güncellemek için modeldeki updateStatus metodunu kullanabilir ve ardından değişiklikleri kaydedebilirsiniz:</p><pre>var task = Task(title: &quot;First Task&quot;, description: &quot;First Task Detail&quot;)<br>task.updateStatus(to: .completed)<br>context.insert(task)</pre><p><strong>4. Task Silmek</strong></p><p>Bir görevi veritabanından kaldırmak için şu şekilde delete metodu kullanılabilir:</p><pre>let task = Task(title: &quot;First Task&quot;, description: &quot;First Task Detail&quot;)<br>context.delete(task)</pre><p><strong>SwiftData’nın Ötesinde: Gelişmiş Özellikler</strong></p><p><strong>1. İlişkisel Veri Modelleri</strong></p><p>Bir görev sisteminde, görevlerin bir proje ile ilişkili olduğunu düşünelim. Aşağıda Project ve Task modelleri arasındaki bire-çok ilişki örneği yer alıyor:</p><pre>@Model<br>  class Project {<br>    var id: String<br>    var name: String<br>    var tasks: [Task]<br>    <br>    init(name: String) {<br>      self.id = UUID().uuidString<br>      self.name = name<br>      self.tasks = []<br>    }<br>}</pre><p>Bir proje oluşturduktan sonra görevi projeye şu şekilde ekleyebilirsiniz:</p><pre>let project = Project(name: &quot;Work Project&quot;)<br>let task = Task(title: &quot;Complete Report&quot;, description: &quot;Finalize the Q4 report.&quot;)<br>project.tasks.append(task)<br>context.insert(project)</pre><p><strong>2. CloudKit ile Veri Senkronizasyonu</strong></p><p>SwiftData’nın CloudKit desteği sayesinde verilerinizi cihazlar arasında otomatik olarak senkronize edebilirsiniz. Böylece kullanıcılarınız aynı verilere farklı cihazlardan erişebilir.</p><p><strong>Sonuç</strong></p><p>SwiftData, veri modelleme ve yönetimi için modern ve güçlü bir çözüm sunuyor. Core Data’nın karmaşık yapısını sadeleştirerek, SwiftUI ile mükemmel bir entegrasyon sağlıyor ve geliştiricilere sezgisel bir deneyim sunuyor.</p><p>Eğer uygulamalarınızda veri kalıcılığına ihtiyaç duyuyorsanız, SwiftData’yı denemenizi öneririm. SwiftData’nın avantajlarını uygulamanızda deneyimledikçe, veri yönetimindeki farkını net bir şekilde hissedeceksiniz.</p><p>Siz SwiftData hakkında ne düşünüyorsunuz? Deneyimlerinizi yorumlarda paylaşmayı unutmayın!</p><p>Buraya kadar okuduğunuz için teşekkür ederim :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71d42aa80a89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hello Swift Macros]]></title>
            <link>https://medium.com/@mustiozdemir/hello-swift-macros-12aed5ee94e1?source=rss-437c9692c8de------2</link>
            <guid isPermaLink="false">https://medium.com/p/12aed5ee94e1</guid>
            <category><![CDATA[swift-macros]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mustafa Özdemir]]></dc:creator>
            <pubDate>Fri, 10 Jan 2025 09:57:30 GMT</pubDate>
            <atom:updated>2025-01-10T09:57:30.605Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey there! Today, we’re talking about something super exciting in the Swift. If you’ve been wondering what they are and how they work, you’re in the right place. Let’s see how Macros can make your life easier. Swift Macros were officially introduced with <strong>Swift 5.9</strong>, announced during <strong>WWDC 2023.</strong></p><p>They are a new way for you to extend Swift with new kinds of expressions, allow creating of expressive libraries, and eliminate extraneous boilerplate.</p><p>If you want to clean your code, macros are here to help you.</p><p>Here is what you need to have,</p><ul><li><strong>Xcode Version</strong>: You’ll need Xcode 15 or later</li><li><strong>iOS Version</strong>: These work with iOS 17 or newer, so make sure your deployment targets are up-to-date.</li><li>macOS 14, watchOS 10, and tvOS 17</li></ul><p>Before dive into Macros we first understand what SwiftSyntax library stands for.</p><p><strong>SwiftSyntax</strong> is a collection of Swift libraries that allow you to parse, inspect, generate, and adjust Swift source code. It was initially developed by Apple and is currently maintained as an open-source library with many contributors.</p><p>SwiftSyntax is a powerful library for working with Swift code in an organized way. Whether you want to build a linter, code formatter, or even compile-time macros, SwiftSyntax gives you low-level control over Swift source code and helps you automate code analysis and transformation tasks.</p><h3>Macros</h3><h3>What Are Swift Macros?</h3><p>Swift is famous for being clean and powerful and now, it is even better with the introduction of macros. But what are macros exactly? Think of them as your little helpers that handle the repetitive stuff in your code so you don’t have to write. Macros transform your code during the compilation process. They can add new features, simplify tasks, and get rid of boilerplate code. The result? Cleaner, easier-to-read, and maintainable code that makes you look like a coding rockstar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*3TzOx7M9UzJkKFBAOLc5YQ@2x.png" /><figcaption>What are Swift Macros?</figcaption></figure><p>There are two types of macros in general:</p><h3>Freestanding Macros</h3><p>Appear on their own, without being attached to a declaration, like functions, but they execute at compile time and generate code</p><h3><em>Attached macros</em></h3><p>Modifies the declaration that they’re attached to. They are used to modify or generate additional code for those declarations.</p><p>How to write Macro<br>Macros are created as a standalone Swift Package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a9gW7jM8gyV-5HKsmrCzGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LQNQSpzeDrWrpGViQxxKgA.png" /></figure><p>freestanding Macro Example</p><pre>@freestanding(expression)<br>public macro greeting(_ name: String) -&gt; String = #externalMacro(module: &quot;RoofMacroMacros&quot;, type: &quot;GreetingMacro&quot;)</pre><p>Expansion</p><pre>public struct GreetingMacro: ExpressionMacro {<br>  public static func expansion(<br>    of node: some FreestandingMacroExpansionSyntax,<br>    in context: some MacroExpansionContext<br>  ) -&gt; ExprSyntax {<br>    guard let argument = node.argumentList.first?.expression.as(StringLiteralExprSyntax.self)?.segments.first?.description else {<br>      fatalError(&quot;compiler bug: the macro does not have any arguments&quot;)<br>    }<br><br>    return ExprSyntax(StringLiteralExprSyntax(content: &quot;Hello, \(argument)&quot;))<br>  }<br>}</pre><p>Using</p><pre>#greeting(&quot;Mustafa&quot;)<br>// prints Hello, Mustafa</pre><p>freestanding macros can be <strong>Expression Macro, Declaration Macro or Member Macro</strong></p><p>1. <strong>Expression Macro</strong></p><p>An expression macro generates a value and can be used in place of any regular expression in the code.</p><p><strong>Example</strong>:</p><pre>let greeting = #uppercase(&quot;hello&quot;) // Generates &quot;HELLO&quot; at compile time</pre><p>2. <strong>Declaration Macro</strong></p><p>A declaration macro generates one or more declarations, such as functions, variables, or types.</p><p><strong>Example</strong>:</p><pre>#createUtilityFunctions // Generates utility functions at compile time</pre><p>3. <strong>Member Macro</strong></p><p>A member macro generates additional members (such as properties or methods) for a type.</p><p><strong>Example</strong>:</p><pre>struct User {<br>    #generateID // Generates an ID property at compile time<br>}</pre><p>Let’s look at <strong>Attached Macro Types</strong></p><p>1. <strong>Attribute Macro</strong></p><p>An attribute macro is attached to a declaration (like a function or a variable) and can modify or enhance it.</p><p><strong>Example</strong>:</p><p>Suppose we have an enum</p><pre>enum Direction {<br>  case north<br>  case south<br>  case east<br>  case west<br>}</pre><p>we want to print the title value of each enum case</p><pre>@attached(member, names: named(title))<br>public macro EnumTitle() = #externalMacro(module: &quot;RoofMacroMacros&quot;, type: &quot;EnumTitleMacro&quot;)</pre><pre>public struct EnumTitleMacro: MemberMacro {<br>  public static func expansion(<br>    of node: AttributeSyntax,<br>    providingMembersOf declaration: some DeclGroupSyntax,<br>    in context: some MacroExpansionContext<br>  ) throws -&gt; [DeclSyntax] {<br>    <br>    guard let enumDel = declaration.as(EnumDeclSyntax.self) else {<br>      fatalError(&quot;This macro only applicable on Enum types&quot;)<br>    }<br>    <br>    let members = enumDel.memberBlock.members<br>    let caseDecl = members.compactMap { $0.decl.as(EnumCaseDeclSyntax.self) }<br>    let cases = caseDecl.compactMap { $0.elements.first?.name.text }<br>    <br>    var title = &quot;&quot;&quot;<br>    var title: String {<br>      switch self {<br>    &quot;&quot;&quot;<br>    <br>    for titleCase in cases {<br>      title += &quot;case .\(titleCase):&quot;<br>      title += &quot;return \&quot;\(titleCase.capitalized)\&quot;&quot;<br>    }<br>    <br>    title += &quot;&quot;&quot;<br>      }<br>    }<br>    &quot;&quot;&quot;<br>   <br>    return [DeclSyntax(stringLiteral: title)]<br>  }<br>}</pre><p>So that with this Macro, we can attach it</p><pre>@EnumTitle<br>enum Direction {<br>  case north<br>  case south<br>  case east<br>  case west<br>}</pre><p>Using</p><pre>print(Direction.west.title)<br>// prints West</pre><p>We can apply this EnumMacro to any Enum in our application.</p><p>2. <strong>Member Attribute Macro</strong></p><p>A member attribute macro is applied to individual members of a type and can modify or extend them.</p><p><strong>Example</strong>:</p><pre>struct User {<br>    @validate<br>    var name: String<br>}</pre><p>3. <strong>Peer Macro</strong></p><p>A peer macro generates additional peer declarations alongside the annotated declaration.</p><p><strong>Example</strong>:</p><pre>@generateTestFunction<br>func add(a: Int, b: Int) -&gt; Int {<br>    return a + b<br>}<br>// Generates a corresponding test function for `add`</pre><p>4. <strong>Conformance Macro</strong></p><p>A conformance macro automatically adds protocol conformance to a type and generates the required methods.</p><p><strong>Example</strong>:</p><pre>@AutoEquatable<br>struct User {<br>    let id: Int<br>    let name: String<br>}<br>// Generates Equatable conformance for `User`</pre><p><strong>Conclusion<br></strong>Swift macros are allow compile-time code generation, reducing boilerplate and improving code clarity. The freestanding macros are great for generating expressions or declarations independently, while attached macros are ideal for enhancing existing declarations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kpEFHJP8S3hCQbjltXW4AA.png" /></figure><p>Thanks for reading :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12aed5ee94e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hello Swift UI]]></title>
            <link>https://medium.com/@mustiozdemir/hello-swift-ui-bd5f7892e7c4?source=rss-437c9692c8de------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd5f7892e7c4</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[declarative-programming]]></category>
            <dc:creator><![CDATA[Mustafa Özdemir]]></dc:creator>
            <pubDate>Fri, 10 Jan 2025 09:10:02 GMT</pubDate>
            <atom:updated>2025-01-10T09:10:02.523Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey there, today I am talking about Swift UI. Before diving into Swift UI, let me explain an important thing.</p><h4><strong>Imperative vs Declarative Programming</strong></h4><p>When working with user interfaces (or any programming paradigm in general), there are two common approaches <strong>imperative</strong> and <strong>declarative</strong>.</p><p><strong>Imperative Programming</strong></p><p>In <strong>imperative programming</strong>, you write code that describes <em>how</em> the program should accomplish tasks. You give explicit instructions, step by step, to achieve the desired outcome.</p><p>For example, in UIKit, if you want to create a UILabel and center it on the screen, you’d typically do something like this:</p><pre>let label = UILabel()<br>label.text = &quot;Hello, UIKit!&quot;<br>label.textAlignment = .center<br>label.font = UIFont.systemFont(ofSize: 20)<br>label.frame = CGRect(x: 0, y: 0, width: 200, height: 50)<br>label.center = view.center<br>view.addSubview(label)</pre><p>Here, you are telling the framework <em>exactly how</em> to create the label, configure its properties, position it, and add it to the view hierarchy. You’re in control of every step, which gives flexibility but also adds complexity.</p><p><strong>Declarative Programming</strong></p><p>In <strong>declarative programming</strong>, instead of describing <em>how</em> to do something, you describe <em>what</em> you want, and the framework figures out the details for you.</p><p>Here’s how you’d achieve the same result in SwiftUI:</p><pre>struct ContentView: View {<br>    var body: some View {<br>        Text(&quot;Hello, SwiftUI!&quot;)<br>            .font(.system(size: 20))<br>            .multilineTextAlignment(.center)<br>            .frame(maxWidth: .infinity, maxHeight: .infinity)<br>    }<br>}</pre><p>In this example, you don’t worry about manually creating a label, setting its frame, or adding it to a view hierarchy. You simply describe what you want — a piece of text centered in the view — and SwiftUI handles the rest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVv4cblUS3tledxsrImWJA.png" /></figure><p>If we understand what Declarative Programming is, we can continue on Swift UI.</p><p><strong>What is SwiftUI?</strong></p><p><strong>SwiftUI</strong> is a UI framework that allows developers to build user interfaces across all Apple platforms using a unified codebase. Unlike UIKit, which follows an imperative approach, SwiftUI is declarative. Instead of writing step-by-step instructions on how to build the UI, you describe what the UI should look like, and SwiftUI takes care of the rest.</p><p><strong>Key Features of SwiftUI</strong></p><p>• <strong>Declarative Syntax</strong>: Focus on what you want, not how to achieve it.</p><p>• <strong>Cross-Platform Support</strong>: Write once, run on iOS, macOS, watchOS, and tvOS.</p><p>• <strong>Live Previews</strong>: See your UI updates in real time without rebuilding the app.</p><p>• <strong>Automatic Dark Mode Support</strong>: SwiftUI makes it easy to support both light and dark themes.</p><ul><li><strong>Seamless Integration with Combine</strong>: Reactive programming becomes simpler with SwiftUI’s state-driven approach.</li></ul><p>Before diving into code, make sure you have the right setup:</p><p>1. <strong>Xcode Version</strong>: SwiftUI requires Xcode 11 or later. For the best experience, use the latest stable version of Xcode.</p><p>2. <strong>Swift Version</strong>: SwiftUI works with Swift 5.1 and above.</p><p>3. <strong>Project Setup</strong>: When creating a new project in Xcode, choose the “App” template and select SwiftUI as the interface option.</p><p><strong>Basic Building Blocks of SwiftUI</strong></p><p>SwiftUI provides several core views that you can combine to build your UI. Let’s start with a few of the most common ones.</p><p><strong>Stacks: VStack, HStack, and ZStack</strong></p><p>In SwiftUI, stacks are fundamental for arranging views.</p><p><strong>VStack (Vertical Stack)</strong></p><pre>VStack {<br>    Text(&quot;Welcome to SwiftUI&quot;)<br>        .font(.title)<br>        .padding()<br>    Button(&quot;Click Me&quot;) {<br>        print(&quot;Button tapped&quot;)<br>    }<br>}</pre><p>A VStack arranges its child views vertically. You can customize the spacing and alignment as needed.</p><p><strong>HStack (Horizontal Stack)</strong></p><pre>HStack {<br>    Image(systemName: &quot;star.fill&quot;)<br>    Text(&quot;Favorite&quot;)<br>}</pre><p>Similarly, HStack arranges its child views horizontally.</p><p><strong>ZStack (Overlapping Stack)</strong></p><pre>ZStack {<br>    Color.blue<br>    Text(&quot;Hello, ZStack!&quot;)<br>        .foregroundColor(.white)<br>}</pre><p>A ZStack overlays its child views on top of each other.</p><p><strong>State Management in SwiftUI</strong></p><p>State management is a key concept in any UI framework, and SwiftUI makes it easy with property wrappers. Let’s break down the most commonly used ones:</p><p><strong>@State</strong></p><p>@State is used for managing local state within a view. When the state changes, the view automatically updates.</p><pre>struct CounterView: View {<br>    @State private var count = 0<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Count: \(count)&quot;)<br>            Button(&quot;Increment&quot;) {<br>                count += 1<br>            }<br>        }<br>    }<br>}</pre><p><strong>@Binding</strong></p><p>@Binding allows a child view to modify a parent view’s state.</p><pre>struct ParentView: View {<br>    @State private var isOn = false<br><br>    var body: some View {<br>        ToggleView(isOn: $isOn)<br>    }<br>}<br><br>struct ToggleView: View {<br>    @Binding var isOn: Bool<br><br>    var body: some View {<br>        Toggle(&quot;Switch&quot;, isOn: $isOn)<br>    }<br>}</pre><p><strong>Navigation in SwiftUI</strong></p><p>Building a multi-screen app is straightforward with NavigationView and NavigationLink.</p><pre>import SwiftUI<br><br>struct ContentView: View {<br>    var body: some View {<br>        NavigationView {<br>            List(1..&lt;6) { index in<br>                NavigationLink(destination: DetailView(index: index)) {<br>                    Text(&quot;Item \(index)&quot;)<br>                }<br>            }<br>            .navigationTitle(&quot;Items&quot;)<br>        }<br>    }<br>}<br><br>#Preview {<br>    ContentView()<br>}</pre><p><strong>Modifiers</strong></p><p>In SwiftUI, you can apply modifiers to views to customize their appearance and behavior.</p><p><strong>Examples of Common Modifiers</strong></p><p>• .padding(): Adds padding around a view.</p><p>• .background(): Sets the background of a view.</p><p>• .cornerRadius(): Rounds the corners of a view.</p><p>• .shadow(): Adds a shadow effect to a view.</p><pre>Text(&quot;SwiftUI Modifiers&quot;)<br>    .font(.headline)<br>    .padding()<br>    .background(Color.yellow)<br>    .cornerRadius(10)<br>    .shadow(radius: 5)</pre><p><strong>Adding Animations<br></strong>Animations in SwiftUI are simple yet powerful. You can add implicit or explicit animations using the .animation() modifier or withAnimation block.</p><pre>struct AnimatedView: View {<br>    @State private var isScaled = false<br><br>    var body: some View {<br>        Button(&quot;Tap Me&quot;) {<br>            isScaled.toggle()<br>        }<br>        .scaleEffect(isScaled ? 1.5 : 1.0)<br>        .animation(.easeInOut, value: isScaled)<br>    }<br>}</pre><p><strong>Pros and Cons of SwiftUI</strong></p><p><strong>Pros</strong></p><p>• <strong>Faster Development</strong>: You don’t have to think how to layout these views, you tell the Swift UI and the compiler handles the rest.</p><p>• <strong>Live Previews</strong>: You can see the result while coding on the left pane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iUpm1uwIBnHToAGLHS-sZg.png" /></figure><p>• <strong>Cross-Platform</strong>: Write once, run everywhere.</p><p><strong>Cons</strong></p><p>• <strong>Limited Backward Compatibility</strong>: SwiftUI requires iOS 13+.</p><p>• <strong>UIKit Interoperability</strong>: In some cases, you may still need to use UIKit components.</p><p><strong>Conclusion</strong></p><p>Learning SwiftUI might not easy at first, but it’s worth the effort. Start with small projects, experiment with different views, and make use of Xcode’s live preview feature to speed up your workflow. Once you get comfortable, you’ll appreciate how much more intuitive and efficient SwiftUI is compared to traditional UIKit development.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd5f7892e7c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift UI — In Action]]></title>
            <link>https://medium.com/@mustiozdemir/swift-ui-in-action-a9d240aafed1?source=rss-437c9692c8de------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9d240aafed1</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Mustafa Özdemir]]></dc:creator>
            <pubDate>Fri, 10 Jan 2025 09:05:58 GMT</pubDate>
            <atom:updated>2025-01-10T09:07:00.379Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift UI — In Action</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*9xTRMpxM6nahZMtS36dTgg.png" /></figure><p>As we talked on my previous post (Hello, Swift UI) Swift UI is a declarative UI framework which produces iOS, macOS, tvOS, watchOS, visionOs applications from shared codebase.</p><p>Let’s start developing small demo project to understand more. Our Application name is MovieApp.</p><p>Movie app basically</p><p>Create New Project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cOOfow0nfT7_y8tkVzg4Nw.png" /></figure><p>First of all Go to <a href="https://www.themoviedb.org/">themoviedb</a> and grab your api key :) And then go back to Xcode to start creating the app.</p><p>Networking</p><p>Create MovieService.swift file</p><pre>struct MovieService {<br><br>  static let shared = MovieService()<br><br>  let baseURL = URL(string: &quot;https://api.themoviedb.org/3&quot;)!<br>  let apiKey = &quot;YOUR_API_KEY&quot;<br><br>  public enum APIError: Error {<br>    case noResponse<br>    case jsonDecodingError(error: Error)<br>    case networkError(error: Error)<br>  }<br><br>  public enum Endpoint {<br>    case popular, topRated, upcoming<br>    <br>    func path() -&gt; String {<br>      switch self {<br>      case .popular:<br>        return &quot;movie/popular&quot;<br>      case .topRated:<br>        return &quot;movie/top_rated&quot;<br>      case .upcoming:<br>        return &quot;movie/upcoming&quot;<br>      }<br>    }<br>  }<br>  <br>  public func GET&lt;T: Codable&gt;(<br>    endpoint: Endpoint,<br>    params: [String: String]?,<br>    completionHandler: @escaping (Result&lt;T, APIError&gt;) -&gt; Void<br>  ) {<br>    let queryURL = baseURL.appendingPathComponent(endpoint.path())<br>    var components = URLComponents(url: queryURL, resolvingAgainstBaseURL: true)!<br>    components.queryItems = [<br>      URLQueryItem(name: &quot;api_key&quot;, value: apiKey),<br>      URLQueryItem(name: &quot;language&quot;, value: Locale.preferredLanguages.first),<br>      URLQueryItem(name: &quot;region&quot;, value: &quot;TR&quot;)<br>    ]<br>    if let params = params {<br>        for (_, value) in params.enumerated() {<br>            components.queryItems?.append(URLQueryItem(name: value.key, value: value.value))<br>        }<br>    }<br>    var request = URLRequest(url: components.url!)<br>    request.httpMethod = &quot;GET&quot;<br>    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in<br>      guard let data = data else {<br>        DispatchQueue.main.async {<br>          completionHandler(.failure(.noResponse))<br>        }<br>        return<br>      }<br>      guard error == nil else {<br>        DispatchQueue.main.async {<br>          completionHandler(.failure(.networkError(error: error!)))<br>        }<br>        return<br>      }<br>      do {<br>        let decoder = JSONDecoder()<br>        let object = try decoder.decode(T.self, from: data)<br>        DispatchQueue.main.async {<br>          completionHandler(.success(object))<br>        }<br>      } catch let error {<br>        DispatchQueue.main.async {<br>          completionHandler(.failure(.jsonDecodingError(error: error)))<br>        }<br>      }<br>    }<br>    task.resume()<br>  }<br>}</pre><p>Response Models</p><p>Create new file and give its name : ApiResponse</p><pre>import Foundation<br><br>struct ApiResponse&lt;T: Codable&gt;: Codable {<br>  let page: Int?<br>  let total_results: Int?<br>  let total_pages: Int?<br>  let results: [T]<br>}</pre><p>T: stands for any Codable file ( Generic)</p><p>And create Movie.swift file</p><pre>import Foundation<br><br>struct Movie: Codable, Identifiable, Hashable {<br>  let id: Int?<br>  let title: String?<br>  let overview: String?<br>  let release_date: String?<br>  let vote_average: Double?<br>  let poster_path: String?<br><br>  var poster: URL? {<br>    guard let posterPath = poster_path else { return nil }<br>    return URL(string: &quot;https://image.tmdb.org/t/p/original\(posterPath)&quot;)<br>  }<br>}</pre><p>These ApiResponse and Movie files are our network response models. As you may guess, we use Movie for T in ApiResponse model. We expect from api to give us results as a Movie objects. I also add a computed property on Movie model, poster, which creates full image URL from poster_path object.</p><p>So, our networking part seems OK. Let’s continue with MovieListViewModel file.</p><pre>import Foundation<br><br>final class MovieListViewModel: ObservableObject {<br>  <br>  @Published var movies: [Movie] = []<br>  @Published var isLoading = false<br>  <br>  var currentPage = 1<br><br>  func getPopularMovies() {<br>    isLoading = true<br>    MovieService.shared.GET(<br>      endpoint: .popular,<br>      params: [&quot;page&quot;: &quot;\(currentPage)&quot;]<br>    ) { (result: Result&lt;ApiResponse&lt;Movie&gt;, MovieService.APIError&gt;) in<br>      switch result {<br>      case .success(let success):<br>        self.movies.append(contentsOf: success.results)<br>      case .failure(let failure):<br>        print(failure.localizedDescription)<br>      }<br>      self.isLoading = false<br>    }<br>  }<br>  <br>  func loadMoreItems() {<br>    currentPage += 1<br>    getPopularMovies()<br>  }<br>  <br>}</pre><p>Observable Object</p><p>In SwiftUI, ObservableObject is a protocol that allows an object to be observed for changes. When an object conforming to ObservableObject publishes changes, SwiftUI views that are observing the object can react to those changes and update themselves accordingly.</p><p><strong>How It Works</strong></p><p>1. An object conforms to the ObservableObject protocol.</p><p>2. Properties inside the object are marked with the @Published property wrapper, indicating that changes to these properties should trigger view updates.</p><p>3. Views use the @StateObject or @ObservedObject property wrapper to subscribe to the ObservableObject.</p><p>4. When a @Published property changes, SwiftUI automatically refreshes the view.</p><p>Now it is time to create our MovieListView file</p><pre>import SwiftUI<br><br>struct MovieListView: View {<br>  <br>  @ObservedObject var viewModel = MovieListViewModel()<br>  <br>  var body: some View {<br>    NavigationStack {<br>      List {<br>        ForEach(viewModel.movies) { movie in<br>          NavigationLink(destination: MovieDetail(movie: movie)) {<br>            MovieView(movie: movie)<br>          }<br>        }<br>        .listRowSeparator(.hidden)<br>        if !viewModel.movies.isEmpty {<br>          lastRowView<br>        }<br>      }<br>      .listStyle(.plain)<br>      .onAppear {<br>        viewModel.getPopularMovies()<br>      }<br>      .navigationTitle(&quot;Movies&quot;)<br>    }<br>  }<br>  <br>  var lastRowView: some View {<br>    HStack {<br>      Spacer()<br>      VStack {<br>        Text(&quot;Loading more items...&quot;)<br>        ActivityIndicator(isAnimating: $viewModel.isLoading)<br>      }<br>      Spacer()<br>    }<br>    .padding()<br>    .onAppear {<br>      DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {<br>        viewModel.loadMoreItems()<br>      })<br>    }<br>  }<br>  <br>}<br><br>#Preview {<br>  MovieListView()<br>}</pre><p>We defined a view called MovieListView that displays a list of movies. The view uses a MovieListViewModel object to fetch and manage the movie data, and it provides a navigation link for each movie that leads to a detailed view. Additionally, it implements lazy loading, where more movies are fetched as the user scrolls down.</p><p><strong>Detailed Breakdown</strong></p><p>1. @ObservedObject var viewModel = MovieListViewModel():</p><p>• viewModel is an instance of MovieListViewModel, which is an ObservableObject.</p><p>• It contains the logic for fetching popular movies and loading more items when needed.</p><p>• The @ObservedObject property wrapper ensures that MovieListView automatically updates whenever viewModel changes.</p><p>2. <strong>NavigationStack</strong>:</p><p>• A NavigationStack is used to manage navigation between views.</p><p>• Each movie in the list is wrapped in a NavigationLink, which navigates to a MovieDetail view when tapped.</p><p>3. <strong>List with </strong>ForEach(viewModel.movies):</p><p>• The List displays a collection of MovieView items, one for each movie in viewModel.movies.</p><p>• ForEach iterates over the list of movies, creating a MovieView for each one.</p><p>• The .listRowSeparator(.hidden) modifier hides the separator lines between list rows.</p><p>4. <strong>Lazy Loading with </strong>lastRowView:</p><p>• If viewModel.movies is not empty, a custom view (lastRowView) is shown at the end of the list.</p><p>• lastRowView displays a loading indicator and triggers the viewModel.loadMoreItems() function when it appears on the screen.</p><p>• A small delay (DispatchQueue.main.asyncAfter) is used to simulate network latency before loading more items.</p><p>5. .onAppear { viewModel.getPopularMovies() }:</p><p>• When the view appears, it triggers viewModel.getPopularMovies(), which fetches the initial list of popular movies.</p><p>6. lastRowView:</p><p>• This view is displayed at the bottom of the list to indicate that more items are being loaded.</p><p>• ActivityIndicator(isAnimating: $viewModel.isLoading) is a custom loading indicator that animates while new items are being fetched.</p><p>• When the lastRowView appears on the screen, viewModel.loadMoreItems() is called to load additional movies.</p><p>7. <strong>Navigation</strong>:</p><p>• Each movie in the list is wrapped in a NavigationLink. When a user taps a movie, they are navigated to a MovieDetail view, where more information about the selected movie is shown.</p><p>Now, let’s continue with MovieDetailView</p><p>Create a new Swift UI View file and named: MovieDetailView</p><pre>struct MovieDetail: View {<br>  <br>  @Environment(\.modelContext) private var context<br>  @Query private var savedMovies: [DataModel]<br>  <br>  private var savedModel: DataModel? {<br>    return savedMovies.filter({$0.id == (movie.id ?? 0)}).first<br>  }<br>  <br>  @State var movie: Movie<br>  <br>    var body: some View {<br>      VStack {<br>        KFImage(movie.poster)<br>          .resizable()<br>          .aspectRatio(contentMode: .fit)<br>          .frame(height: 300)<br>        Text(movie.title ?? &quot;&quot;)<br>        Text(movie.overview ?? &quot;&quot;)<br>      }<br>      .toolbar {<br>        Button(action: {<br>          updateDatabase(movie: movie)<br>        }, label: {<br>          Image(systemName: savedModel == nil ? &quot;heart&quot; : &quot;heart.fill&quot;)<br>        })<br>      }<br>    }<br>  <br>  private func updateDatabase(movie: Movie) {<br>    if let saved = savedModel {<br>      context.delete(saved)<br>    } else {<br>      context.insert(<br>        DataModel(<br>          id: movie.id ?? 0,<br>          name: movie.title ?? &quot;&quot;,<br>          posterPath: movie.poster_path ?? &quot;&quot;<br>        )<br>      )<br>    }<br>  }<br>}</pre><p>I use <a href="https://github.com/onevcat/Kingfisher">Kingfisher</a> for async image loading and caching, you can choose anything you like.</p><p>In MovieDetail you see some Database operations too. I choose Swift Data to persist my favourite movies.</p><p>Steps to mark a movie as a favourite</p><p>Create DataModel.swift file</p><pre>import Foundation<br>import SwiftData<br><br>@Model<br>class DataModel: Identifiable {<br>  @Attribute(.unique) var id: Int<br>  var name: String<br>  var posterPath: URL?<br>  <br>  init(id: Int, name: String, posterPath: String) {<br>    self.id = id<br>    self.name = name<br>    self.posterPath = URL(string: &quot;https://image.tmdb.org/t/p/original\(posterPath)&quot;)<br>  }<br>}</pre><p>we use @Model macro which generates database spesific codes on compile time,</p><p>Grab model context from Environment</p><pre>@Environment(\.modelContext) private var context</pre><p>And insert DataModel object to our modelContext to store. Thanks to Swift Data :)</p><p>Let’s Continue with our FavouriteMoviesView. Create a new file</p><pre>import SwiftUI<br>import SwiftData<br>import Kingfisher<br><br>struct FavouritesView: View {<br>  <br>  @Environment(\.modelContext) private var context<br>  <br>  @Query(sort: \DataModel.name) var movies: [DataModel]<br>  <br>    var body: some View {<br>      NavigationStack {<br>        List {<br>          ForEach(movies) { movie in<br>            HStack {<br>              KFImage(movie.posterPath)<br>                .resizable()<br>                .frame(width: 50, height: 50)<br>                .clipShape(Circle())<br>              Text(movie.name)<br>            }<br>          }<br>          .onDelete(perform: { indexSet in<br>            withAnimation {<br>              for index in indexSet {<br>                context.delete(movies[index])<br>              }<br>            }<br>          })<br>        }<br>      }<br>    }<br>}</pre><p>FavouritesView that displays a list of favorite movies stored in a local data model. It uses SwiftData for data persistence and Kingfisher to load and display movie poster images.</p><p><strong>Detailed Breakdown</strong></p><p>1. @Environment(\.modelContext) private var context:</p><p>• context represents the SwiftData model context, which is used to manage the lifecycle of data and perform CRUD (Create, Read, Update, Delete) operations.</p><p>• This is needed to delete movies from the local database.</p><p>2. @Query(sort: \DataModel.name) var movies: [DataModel]:</p><p>• The @Query property wrapper retrieves the list of favorite movies from the local database, sorted by the name property of the DataModel.</p><p>• movies is an array of DataModel objects, each representing a favorite movie.</p><p>3. NavigationStack:</p><p>• A NavigationStack is used to provide a navigation hierarchy for the view.</p><p>4. List<strong> and </strong>ForEach:</p><p>• A List is used to display the list of favorite movies.</p><p>• ForEach iterates over the movies array, creating a row for each movie.</p><p>• Each row contains:</p><p>• KFImage(movie.posterPath): This uses <strong>Kingfisher</strong> to load and display the movie’s poster image from a URL (posterPath). The image is:</p><p>• Made resizable using .resizable().</p><p>• Set to a size of 50x50.</p><p>• Clipped into a circular shape using .clipShape(Circle()).</p><p>• Text(movie.name): Displays the movie’s name next to the image.</p><p>5. .onDelete(perform:):</p><p>• This modifier enables swipe-to-delete functionality on the list rows.</p><p>• When the user swipes to delete a movie, the closure is executed. Inside the closure:</p><p>• context.delete(movies[index]) deletes the corresponding movie from the database.</p><p>• withAnimation ensures that the deletion is animated smoothly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9d240aafed1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>