<?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 Vishwas Ng on Medium]]></title>
        <description><![CDATA[Stories by Vishwas Ng on Medium]]></description>
        <link>https://medium.com/@vishwasng?source=rss-213d9cabe71d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*iskl9-c3lnBT98Md.jpg</url>
            <title>Stories by Vishwas Ng on Medium</title>
            <link>https://medium.com/@vishwasng?source=rss-213d9cabe71d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 08:08:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vishwasng/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[Building and Understanding the Foundation Model Framework with Code: Part 2]]></title>
            <link>https://medium.com/mobilepeople/building-and-understanding-the-foundation-model-framework-with-code-part-2-eba00dbc8080?source=rss-213d9cabe71d------2</link>
            <guid isPermaLink="false">https://medium.com/p/eba00dbc8080</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[foundation-models]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Vishwas Ng]]></dc:creator>
            <pubDate>Sun, 19 Oct 2025 05:00:39 GMT</pubDate>
            <atom:updated>2025-10-28T07:34:50.623Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1BJOau3FIfc0cTtTybhBbg.jpeg" /><figcaption>Building and Understanding the Foundation Model Framework with Code: Part 2</figcaption></figure><p>From the <a href="https://medium.com/@vishwasng/building-and-understanding-the-foundation-model-framework-with-code-49d5080b3f9d">previous part</a>, we gained an understanding of the FoundationModel framework and its application. Additionally, we noted a few areas for improvement. those are</p><ul><li>Structured Response for the given prompt.</li><li>Improving the user experience.</li></ul><p>If you can recall from the <a href="https://medium.com/mobilepeople/understanding-the-basics-of-foundationmodel-72e5dc08f065">first Article</a>, the response to the prompt can be a <em>structured response,</em> and a <em>Generable </em>macro can be used for the same.</p><p>Let&#39;s create a structure in which we want our response to be</p><pre>@Generable<br>struct myResponseDetail:Equatable {<br>    @Guide(description: &quot;Detail response for given prompt&quot;)<br>    var name:String = &quot;&quot;<br>    @Guide(description: &quot;Detail response for given prompt&quot;)<br>    var Description:String = &quot;&quot;<br>    @Guide(description: &quot;Assert the source URL from where you got information or any URL where you can get more information&quot;)<br>    var url:String = &quot;&quot;<br>}</pre><p>The above code defines a Swift struct named myResponseDetail to encapsulate details related to a response.</p><ul><li>Each property has an @Guide annotation with a description string.</li><li>@Guide is a custom attribute that provides metadata or documentation about each property, which can be used as a reference.</li></ul><p>Now, let&#39;s try to use this struct and try to generate a response</p><pre>let response = try await session.respond(to: &quot;explain UIKit in 100 words&quot;, generating: myResponseDetail.self)</pre><p>so the overall code looks like below</p><pre>import FoundationModels<br>import Playgrounds<br><br>@Generable<br>struct myResponseDetail:Equatable {<br>    @Guide(description: &quot;Detail response for given prompt&quot;)<br>    var name:String = &quot;&quot;<br>    @Guide(description: &quot;Detail response for given prompt&quot;)<br>    var Description:String = &quot;&quot;<br>    @Guide(description: &quot;Assert the source URL from where you got information or any URL where you can get more information&quot;)<br>    var url:String = &quot;&quot;<br>}<br><br>#Playground {<br>    let model = SystemLanguageModel.default<br>    let instruction = &quot;&quot;&quot;<br>        Act as a expert Swift Tutor and always give atleast one code example at the end<br>        &quot;&quot;&quot;<br>    let session = LanguageModelSession(instructions: instruction)<br>    let response = try await session.respond(to: &quot;explain UIKit in 100 words&quot;, generating:myResponseDetail.self)<br>}</pre><p>From the above code, we can see the response as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QghHi__6AwwGTB461chuUQ.png" /></figure><p>As you can see on the bottom right edge of the image, you see the <em>name, description, url </em>details.</p><p>By comparison, you can observe the difference directly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1DwnXVgQQnlMgPKl66CxBA.png" /></figure><p><strong>Left:-</strong> with proper structure, easy to phrase and get details</p><p><strong>Right:-</strong> just string output</p><p>With the above code modifications, we have now addressed the first hurdle we planned for. If you’re wondering, this also enhances our UX experience, but it remains largely unchanged in terms of user interaction.</p><p>How to increase the UX experience?</p><p>One simple way is to streamline the response as it is, instead of showing all at once.</p><p>When you send a prompt to any LLM, the response will be streamed, line by line, with partial data known as tokens. We can use these to improve the UX</p><blockquote>this article concentrates more on how to integrate the on-device LLM to the app. If you are interested in knowing more about how tokenisation works, you can refer <a href="https://developer.apple.com/videos/play/wwdc2025/286"><em>here</em></a></blockquote><p>So let&#39;s try to stream the response, we can do it with the help of the below API</p><pre>var response: myResponseDetail.PartiallyGenerated?<br>let tokens = session.streamResponse(to: prompt,  generating: myResponseDetail.self)<br>for try await token in tokens {<br>     response = token.content<br> }</pre><h3>Explanation:</h3><p><strong>var response: myResponseDetail.PartiallyGenerated?</strong>:</p><ul><li>Declares an optional variable named response of type myResponseDetail.PartiallyGenerated.</li><li>This variable will store the partial or final response content as it is received.</li><li>The optional (?) indicates that the response might initially be nil before any content is assigned.</li></ul><p><strong>let tokens = session.streamResponse(to: prompt, generating: myResponseDetail.self)</strong>:</p><ul><li>Calls a method streamResponse on an session object.</li><li><strong>Purpose</strong>: Starts streaming responses asynchronously for the provided prompt.</li><li>It returns an asynchronous sequence (tokens) which produces tokens (chunks of data or partial responses) over time.</li></ul><p><strong>for try await token in tokens { ... }</strong></p><ul><li>Asynchronously iterates over each token produced by the streaming response.</li><li>try indicates that the code inside may throw an error, so it should be handled accordingly.</li><li>await pauses execution until each new token is available, fitting with Swift&#39;s concurrency model for async sequences.</li></ul><p><strong>response = token.content</strong></p><ul><li>Assigns the content of each token to the response variable.</li><li>Since tokens are streamed asynchronously, this line updates response Repeatedly, as new tokens arrive.</li><li>The final value of response After the loop completes, the last token&#39;s content.</li></ul><p><strong>Finally Summarising</strong></p><ul><li>The above code initiates a streaming request for a generated response based on a prompt.</li><li>It asynchronously receives chunks (tokens) of the response.</li><li>Each token’s content updates the response variable, allowing real-time or partial display of the generated response.</li><li>It leverages Swift’s async/await features for handling asynchronous streams efficiently.</li></ul><p>Let&#39;s try the same changes in the existing code</p><p><strong>ModelGenerator Class</strong></p><pre>//<br>//  ModelGenerator.swift<br>//  Medium_Example<br>//<br>//  Created by Vishwas NG on 13/10/25.<br>//<br><br>import FoundationModels<br>import SwiftUI<br><br>@Generable<br>struct myResponseDetail:Equatable {<br>    @Guide(description: &quot;Detail response for given prompt&quot;)<br>    var name:String = &quot;&quot;<br>    @Guide(description: &quot;Detail response for given prompt&quot;)<br>    var Description:String = &quot;&quot;<br>    @Guide(description: &quot;Assert the source URL from where you got information or any URL where you can get more information&quot;)<br>    var url:String = &quot;&quot;<br>}<br><br>@Observable public class ModelGenerator {<br>    <br>    let model = SystemLanguageModel.default<br>    let session:LanguageModelSession<br>    var response: myResponseDetail.PartiallyGenerated?<br>    <br>    init () {<br>        session =  LanguageModelSession()<br>    }<br>    <br>    func getResponse(for prompt:String) async throws   {<br>        do {<br>            let tokens = session.streamResponse(to: prompt,  generating: myResponseDetail.self)<br>            for try await token in tokens {<br>                response = token.content<br>            }<br>        }<br>        catch {<br>            print(&quot;This is Catch Block \(error.localizedDescription)&quot;)<br>        }<br>    }<br>}</pre><p>The above code reflects as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*LJVe0Qn6_BS4K7cpIXsggA.gif" /></figure><p>From the above gif, you can observe that the loading time has decreased from the previous article. And also improves the User experience.</p><p>With the above code changes/improvements, we were able to improve the user experience.</p><p><strong>Check the availability of the on-device LLM</strong></p><p>The on-device LLM is restricted to newer iPhone models and should also be enabled by the user to use it. This check can be done as below</p><pre>let model = SystemLanguageModel.default<br><br>switch model.availability {<br>        case .available:<br>            print(&quot;Foundation Models is available and ready to go!&quot;)<br>            <br>        case .unavailable(.deviceNotEligible):<br>            print(&quot;The model is not available on this device.&quot;)<br>            <br>        case .unavailable(.appleIntelligenceNotEnabled):<br>            print(&quot;Apple Intelligence is not enabled in Settings.&quot;)<br>            <br>        case .unavailable(.modelNotReady):<br>            print(&quot;The model is not ready yet. Please try again later.&quot;)<br>            <br>        case .unavailable(let other):<br>            print(&quot;The model is unavailable for an unknown reason.&quot;)<br>        }</pre><p><strong>What’s next ?</strong></p><p>The on-device LLM can be used much more useful, if used effectively. It can also be used to get the latest and live data, too, with the help of “Tool calling”. Which will be part of the upcoming article very soon.</p><h4>Source/Reference</h4><p><a href="https://developer.apple.com/videos/play/wwdc2025/286">Meet the Foundation Models framework - WWDC25 - Videos - Apple Developer</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FA8X6hNWX65U%3Fstart%3D4249%26feature%3Doembed%26start%3D4249&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DA8X6hNWX65U&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FA8X6hNWX65U%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa4cb3e64d574e617f6d14f12502b5ec/href">https://medium.com/media/aa4cb3e64d574e617f6d14f12502b5ec/href</a></iframe><p><strong>About Me</strong></p><p><a href="https://www.linkedin.com/in/vishwas-yadav-33522369/">https://www.linkedin.com/in/vishwas-yadav-33522369/</a></p><p><strong>Code Repository</strong></p><p><a href="https://github.com/vishw33/FoundationModel-Demo">GitHub - vishw33/FoundationModel-Demo: Basic example of FoundationModel</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eba00dbc8080" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobilepeople/building-and-understanding-the-foundation-model-framework-with-code-part-2-eba00dbc8080">Building and Understanding the Foundation Model Framework with Code: Part 2</a> was originally published in <a href="https://medium.com/mobilepeople">MobilePeople</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building and Understanding the Foundation Model Framework with Code]]></title>
            <link>https://medium.com/mobilepeople/building-and-understanding-the-foundation-model-framework-with-code-49d5080b3f9d?source=rss-213d9cabe71d------2</link>
            <guid isPermaLink="false">https://medium.com/p/49d5080b3f9d</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[foundation-models]]></category>
            <category><![CDATA[apple-intelligence]]></category>
            <category><![CDATA[writing-prompts]]></category>
            <category><![CDATA[apple]]></category>
            <dc:creator><![CDATA[Vishwas Ng]]></dc:creator>
            <pubDate>Sun, 19 Oct 2025 04:52:08 GMT</pubDate>
            <atom:updated>2025-10-28T07:34:01.488Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GERIJnTv2UpZsEL5Kdhuxw.jpeg" /><figcaption>Building and Understanding the Foundation Model Framework with Code.</figcaption></figure><p>From the <a href="https://medium.com/@vishwasng/understanding-the-basics-of-foundation-models-72e5dc08f065">previous part</a>, we all got the basics of the FoundationModel framework. Let&#39;s get hands-on with it.</p><p>Let’s create a new project and add a filePlayground.swift, or you can directly create a playground file and later move it to the actual project.</p><blockquote>Before jumping into code, you must have used many LLM-based AI services, such as ChatGPT, Claude, and Perplexity, and understand how they work.</blockquote><p>FoundationModel also works similarly, but is hosted on the device with complete privacy protection.</p><p>So the first step will be initialising the LLM and creating the session, so one can send prompts and interact</p><pre>let model = SystemLanguageModel.default<br>let session = LanguageModelSession()</pre><p>Let&#39;s make our first prompt</p><pre> let response = try await session.respond(to: &quot;explain UIKit in 100 words&quot;)</pre><blockquote>PS :- Hoping all know how Prompt works, and how to write an effective prompt to get an accurate result. Here we use basic prompts for our example.</blockquote><pre>import FoundationModels<br>import Playgrounds<br><br>#Playground {<br>    let model = SystemLanguageModel.default<br>    let session = LanguageModelSession()<br>    let response = try await session.respond(to: &quot;explain UIKit in 100 words&quot;)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P10JKJOyYROcqUgwTLIFqQ.png" /></figure><p>You can see from the above image that a simple three-line code can be used to generate a response to a given prompt.</p><h4><strong>Instructions</strong></h4><p>Let’s improve the above code with some enhancements. How can we improve the response from the LLM to the prompt? One way is to set the context or instructions for the session so that the LLM knows exactly which direction to follow. We can set the instruction as shown below while keeping the same prompt.</p><pre>import FoundationModels<br>import Playgrounds<br><br>#Playground {<br>    let model = SystemLanguageModel.default<br>    let instruction = &quot;&quot;&quot;<br>        Act as a expert Swift Tutor and always give atleast one code example at the end<br>        &quot;&quot;&quot;<br>    let session = LanguageModelSession(instructions:instruction)<br>    let response = try await session.respond(to: &quot;explain UIKit in 100 words&quot;)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cmVLDRyIj_Yv_NsdgmeVWg.png" /></figure><p>Even though the prompt is the same, the response is different. The above image provided a small code example based on the instructions.</p><h4><strong>Jumping to the actual project Implementation</strong></h4><p>Let&#39;s make a proper app with UI to use this</p><p>Create a new project and create a class for</p><ul><li>ModelGenerator.swift</li><li>ContentView.swift</li></ul><p><strong>ModelGenerator Class</strong></p><p>This class will be the same as the one we see in the playground file above, but with a proper class structure for use in ContentView. Essentially, it processes the prompt and sends back a response for the view to display on the screen. It will look something like below.</p><pre>//<br>//  ModelGenerator.swift<br>//  Medium_Example<br>//<br>//  Created by Vishwas NG on 11/10/25.<br>//<br><br>import FoundationModels<br>import SwiftUI<br><br>@Observable public class ModelGenerator {<br>    <br>    let model = SystemLanguageModel.default<br>    let session:LanguageModelSession<br>    let instruction = &quot;&quot;&quot;<br>        Act as a expert Swift Tutor and always give atleast one code example at the end<br>        &quot;&quot;&quot;<br>    var response:String = &quot;&quot;<br><br>    <br>    init () {<br>        session = LanguageModelSession(instructions:instruction)<br>    }<br>    <br>    func getResponse(for prompt:String) async throws   {<br>        response = try await session.respond(to: prompt).content<br>        print(response)<br>    }<br>}</pre><p><strong>ContentView</strong></p><p>This is a view that displays the actual response on view. This class basically contains different states where UI updates on it. Will not deep dive into swifUI stuff, but shows how the response is displayed</p><pre>//<br>//  ContentView.swift<br>//  Medium_Example<br>//<br>//  Created by Vishwas NG on 10/10/25.<br>//<br><br>import SwiftUI<br><br>enum CurrentState {<br>    case idle<br>    case loading<br>    case loaded<br>}<br><br>struct ContentView: View {<br>    <br>    @State var gen: ModelGenerator = ModelGenerator()<br>    @State private var state: CurrentState = .idle<br>    @State private var query: String = &quot;&quot;<br>    <br>    var body: some View {<br>        NavigationStack {<br>            ZStack {<br>                LinearGradient(gradient: Gradient(colors: [Color.blue.opacity(0.1), Color.purple.opacity(0.1)]), startPoint: .topLeading, endPoint: .bottomTrailing)<br>                    .edgesIgnoringSafeArea(.all)<br>                <br>                VStack {<br>                    switch state {<br>                    case .idle:<br>                        idleView<br>                    case .loading:<br>                        ProgressView {<br>                            Text(&quot;Loading...&quot;)<br>                                .font(.headline)<br>                                .foregroundColor(.blue)<br>                        }<br>                    case .loaded:<br>                        loadedView<br>                    }<br>                }<br>                .padding()<br>            }<br>            .task {<br>                do {<br>                    self.state = .loading<br>                    try await gen.getResponse(for: &quot;explain UIKit in 1000 words&quot;)<br>                    self.state = .loaded<br>                } catch {<br>                    print(error.localizedDescription)<br>                }<br>            }<br>            .navigationTitle(&quot;FoundationModel Demo&quot;)<br>            .navigationBarTitleDisplayMode(.inline)<br>            .navigationBarItems(trailing: Button(&quot;Reset&quot;) {<br>                withAnimation {<br>                    self.state = .idle<br>                }<br>            })<br>        }<br>    }<br>    <br>    var idleView: some View {<br>        VStack(spacing: 20) {<br>            Text(&quot;Make your Query&quot;)<br>                .font(.title2)<br>                .fontWeight(.semibold)<br>            <br>            TextField(&quot;Enter a language&quot;, text: $query)<br>                .textFieldStyle(RoundedBorderTextFieldStyle())<br>                .padding()<br>            <br>            Button(action: {<br>                withAnimation {<br>                    self.state = .loading<br>                }<br>                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {<br>                    Task {<br>                        self.state = .loading<br>                        try await gen.getResponse(for: query)<br>                        self.state = .loaded<br>                    }<br>                }<br>            }) {<br>                Text(&quot;Submit&quot;)<br>                    .fontWeight(.semibold)<br>                    .foregroundColor(.white)<br>                    .padding()<br>                    .background(LinearGradient(gradient: Gradient(colors: [Color.blue, Color.purple]), startPoint: .leading, endPoint: .trailing))<br>                    .cornerRadius(10)<br>            }<br>        }<br>        .padding(30)<br>        .background(Color.white.opacity(0.8))<br>        .cornerRadius(20)<br>        .shadow(radius: 10)<br>    }<br>    <br>    var loadedView: some View {<br>        ScrollView {<br>            VStack(alignment: .leading, spacing: 20) {<br>                Text(gen.response)<br>                    .multilineTextAlignment(.center)<br>            }.padding(20)<br>        }<br>    }<br>}</pre><p>The result will resemble what is shown in the gif below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*9yAhmJsuHQ_oa75jpOOD8Q.gif" /></figure><p>So, as you can see, you have generated a response to your prompt using an on-device LLM.</p><h4><strong>Take Away</strong></h4><ul><li>You now know how to make use of a simple on-device LLM.</li><li>With simple <strong><em>Instructions</em></strong> on how prompt responses can be improvised.</li><li>A simple UI to display the same.</li></ul><h4><strong>Observation</strong></h4><ul><li>The response is in a String, in fact, a huge string.</li><li>If you want to present on UI with some design/structure, parsing a string is impossible, as the response is not structured.</li><li>Also, you see the loading screen for a longer duration, which is not a good UX.</li></ul><p>So, we observed some concerns in the above point. Let’s strategise the solution.</p><ul><li>First, we need the response in a structured format so that we can easily predict and parse a pattern, regardless of the pattern.</li><li>Second, the loading indicator remains visible for a longer time, even though the response arrives immediately. If we update the view as and when we receive a response, it will result in a better user experience.</li></ul><p>Let&#39;s tackle the above two points in our <a href="https://medium.com/@vishwasng/building-and-understanding-the-foundation-model-framework-with-code-eba00dbc8080">next article</a>.</p><h4>Source/Reference</h4><p><a href="https://developer.apple.com/videos/play/wwdc2025/286">Meet the Foundation Models framework - WWDC25 - Videos - Apple Developer</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FA8X6hNWX65U%3Fstart%3D4249%26feature%3Doembed%26start%3D4249&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DA8X6hNWX65U&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FA8X6hNWX65U%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa4cb3e64d574e617f6d14f12502b5ec/href">https://medium.com/media/aa4cb3e64d574e617f6d14f12502b5ec/href</a></iframe><p><strong>About Me</strong></p><p><a href="https://www.linkedin.com/in/vishwas-yadav-33522369/">https://www.linkedin.com/in/vishwas-yadav-33522369/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49d5080b3f9d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobilepeople/building-and-understanding-the-foundation-model-framework-with-code-49d5080b3f9d">Building and Understanding the Foundation Model Framework with Code</a> was originally published in <a href="https://medium.com/mobilepeople">MobilePeople</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the basics of FoundationModel]]></title>
            <link>https://medium.com/mobilepeople/understanding-the-basics-of-foundationmodel-72e5dc08f065?source=rss-213d9cabe71d------2</link>
            <guid isPermaLink="false">https://medium.com/p/72e5dc08f065</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[apple-intelligence]]></category>
            <category><![CDATA[writing-prompt-response]]></category>
            <dc:creator><![CDATA[Vishwas Ng]]></dc:creator>
            <pubDate>Sat, 18 Oct 2025 07:12:28 GMT</pubDate>
            <atom:updated>2025-10-28T07:33:00.429Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DpcsXbLRaWaCQLxz0XMp2A.jpeg" /><figcaption>Understanding the basics of FoundationModel</figcaption></figure><p>Apple has introduced a new framework, <em>FoundationModel. </em>This framework brings the common Language model to on-device iPhones.</p><p>This helps in the generation of</p><ul><li>basic suggestions.</li><li>content generation.</li><li>content summarisation.</li></ul><p>The Foundation Model helps in response generation for the given prompt. The prompt can be anything within the moral regulations.</p><p>With the current trend towards “AI” and numerous LLMs, I hope I don&#39;t need to explain what prompts are.</p><p>Let&#39;s jump to understanding the key API/Class of the framework</p><ul><li>SystemLanguageModel</li><li>@Generable</li><li>@Guide</li></ul><h3><strong>SystemLanguageModel</strong></h3><p>SystemLanguageModel is part of Apple’s on-device machine learning capabilities, specifically for natural language processing. It’s a powerful feature introduced in iOS 17 that allows developers to leverage Apple’s language models directly on the device. Here’s a more accurate overview:</p><p>SystemLanguageModel provides access to Apple’s on-device text foundation model, enabling natural language processing tasks without requiring network connectivity or sending data to external servers.</p><p><strong>Key Features:</strong></p><ul><li>On-device processing</li><li>Privacy-preserving (data doesn’t leave the user’s device)</li><li>Part of the Apple Intelligence framework</li></ul><p><em>Response in SystemLanguageModel </em>is of 2 types</p><ul><li>Non-Structured Response:- Where the response is a long string without any proper way to phrase.</li><li>Structured Response:- where the response will be based on the defined structure, which will make for easy parsing.</li></ul><p>You can set instructions and pass prompts to the model for better responses. The basic initialisation can be as follows</p><pre>let model = SystemLanguageModel.default</pre><h3><strong>Generable</strong></h3><p>Basically, Generbale is a Macro used to annotate your Swift structure or enumeration. This macro allows the model to respond to prompts by generating an instance of your type.</p><p>This aligns your response in a structured form.</p><p>@Generable is a macro that annotates Swift structures or enumerations, enabling them to be used with SystemLanguageModel for generating structured responses to prompts.</p><p><strong>Usage:</strong></p><ul><li>Allows SystemLanguageModel to generate instances of your custom types</li><li>Helps in creating structured outputs from language model responses</li></ul><p><strong>Basic usage and integration</strong></p><pre>@Generable<br>struct Res:Identifiable, Hashable  {<br>....<br>....<br>}<br><br>let response = try await session.respond(to: prompt, generating:[Res].self).content</pre><h3><strong>Guide</strong></h3><p>Guide is a powerful tool used in conjunction with @Generable to provide more control over the generated values. is used to influence or constrain the values that can be generated for properties within a Generable type.</p><p><strong>Uses:</strong></p><ul><li>Provides additional context or constraints to the language model</li><li>Helps in generating more accurate and relevant values for specific properties</li></ul><p><strong>Advantages:</strong></p><ul><li>Improves the quality and relevance of generated content</li><li>Allows for fine-tuning of generated structures without changing the overall type definition</li><li>Enhances control over the output format and content</li></ul><pre>@Generable<br>struct Res:Identifiable, Hashable  {<br>@Guide(description: &quot;response name&quot;)<br>    var name:String<br>    @Guide(description: &quot;Name of the country&quot;)<br>    let country:String<br>}</pre><p>Now you know the basics of FoundationModel and a few APIs (or Macros) that we use primarily in our code.</p><p>Will come up with the code example in the <a href="https://medium.com/@vishwasng/building-and-understanding-the-foundation-model-framework-with-code-49d5080b3f9d"><em>next part</em></a> soon…….</p><h4><strong>Source/Reference</strong></h4><p><a href="https://developer.apple.com/videos/play/wwdc2025/286">Meet the Foundation Models framework - WWDC25 - Videos - Apple Developer</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FA8X6hNWX65U%3Fstart%3D4249%26feature%3Doembed%26start%3D4249&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DA8X6hNWX65U&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FA8X6hNWX65U%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa4cb3e64d574e617f6d14f12502b5ec/href">https://medium.com/media/aa4cb3e64d574e617f6d14f12502b5ec/href</a></iframe><p><strong>About Me</strong></p><p><a href="https://www.linkedin.com/in/vishwas-yadav-33522369/">https://www.linkedin.com/in/vishwas-yadav-33522369/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72e5dc08f065" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobilepeople/understanding-the-basics-of-foundationmodel-72e5dc08f065">Understanding the basics of FoundationModel</a> was originally published in <a href="https://medium.com/mobilepeople">MobilePeople</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crafting Stunning UIs with SwiftUI: Mesh Gradients]]></title>
            <link>https://medium.com/mobilepeople/crafting-stunning-uis-with-swiftui-mesh-gradients-d5894cf38fc7?source=rss-213d9cabe71d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5894cf38fc7</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Vishwas Ng]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 04:30:51 GMT</pubDate>
            <atom:updated>2025-04-13T12:04:14.977Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*feFMrCszDap3um8Ls_qo0g.png" /></figure><p>Hi, with every new release of Swift and iOS, SwiftUI gets mature and stable APIS with new features and libraries. We are going to discuss a couple of those features today.</p><ul><li>Mesh Gradient</li><li>TextRenderer</li></ul><h3><strong>Mesh Gradient</strong></h3><p>If you are a seasoned iOS developer, you are not new to colours and gradients, with existing Linear and Angular Gradients. Apple has introduced a new gradient called <a href="https://developer.apple.com/documentation/SwiftUI/MeshGradient">Mesh Gradient</a></p><p>Let&#39;s get familiar with it, Mesh means something like a net or grid pattern. A simple Google search for MeshGradient gives the following answer</p><blockquote>a type of gradient where the color transitions are defined by a grid of points (vertices) and their associated colors</blockquote><p>Let&#39;s take a simple syntax,</p><pre>  MeshGradient(width:  Int,<br>               height: Int,<br>               points: [SIMD2&lt;Float&gt;],<br>               colors: [Color] )</pre><p>Consider the image below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*xxepcKUYw1shh4jUwzBjUg.png" /></figure><p>Consider the Square as your screen, it will have</p><ul><li>width (the width of the mesh, i.e. the number of vertices per row)</li><li>height (the height of the mesh, i.e. the number of vertices per column)</li><li>origin (0,0 represents start of x,y ie top left)</li></ul><p>So all value comes within this range, for example</p><p>3by3 grid will have sets</p><pre>[0,0],   [0.5,0],   [1,0],<br>[0,0.5], [0.5,0.5], [1, 0.5],<br>[0,1],   [0.5,1],   [1,1]</pre><p>So by syntax</p><pre>MeshGradient(width:  Int,<br>               height: Int,<br>               points: [SIMD2&lt;Float&gt;],<br>               colors: [Color] )<br>/*<br>MeshGradient(width: 3,<br>             height: 3,<br>             points: [[0,0],   [0.5,0],   [1,0],<br>                      [0,0.5], [0.5,0.5], [1, 0.5],<br>                      [0,1],   [0.5,1],   [1,1]],<br>             colors: [.red, .green, .blue, .white, .black] )<br>*/</pre><p>So basically, you define how the screen will be divided into a mesh format and the color associated with each, voila, the rest rendering will be taken care of by iOS</p><p>The code can be as simple as</p><pre>struct ContentView: View {<br>    <br>    var bal:[SIMD2&lt;Float&gt;] = [ [0,0], [0.5,0], [1,0],<br>                               [0,0.5], [0.5,0.5], [1, 0.5],<br>                               [0,1], [0.5,1], [1,1]]<br>    <br>    static var color:[Color] = [.red, .green,.blue ,.yellow,.orange,.mint,.purple,.teal]<br>    <br>    var body: some View {<br>        ZStack {<br>            <br>            MeshGradient(width: 3,<br>                         height: 3,<br>                         points: bal,<br>                         colors: color)<br>            .ignoresSafeArea(.all)<br>        }<br>    }<br>}<br><br>#Preview {<br>    ContentView()<br>}</pre><p>The above code results in the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WqeF7Vtrlcn8ZJLC8i1nYQ.png" /></figure><p>If you wonder if you somehow have seen something similar, it&#39;s the new iPhone wallpapers.</p><p>While on the same topic, we can make something fun like Random MeshGradient Generator</p><pre><br>import SwiftUI<br><br>struct ContentView: View {<br>    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()<br>    <br>    var bal:[SIMD2&lt;Float&gt;] = [ [0,0], [0.5,0], [1,0],<br>                               [0,0.5], [0.5,0.5], [1, 0.5],<br>                               [0,1], [0.5,1], [1,1]]<br>    <br>    static var color:[Color] = [.red, .green,.blue ,.yellow,.orange,<br>                                .mint,.purple,.teal,.black]<br>    <br>    static func randomColor() -&gt; [Color] {<br>        (0...9).map { _ in<br>            color.randomElement()!<br>        }<br>    }<br>    <br>    @State var randomClr:[Color] = randomColor()<br>    <br>    var body: some View {<br>        ZStack {<br>            <br>            MeshGradient(width: 3,<br>                         height: 3,<br>                         points: bal,<br>                         colors: randomClr )<br>            .ignoresSafeArea(.all)<br>            .onReceive(timer) { _ in<br>                randomClr = ContentView.randomColor()<br>            }<br>        }<br>    }<br>}<br><br>#Preview {<br>    ContentView()<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*eZ-q_en3sRP2GeOViJPF6g.gif" /></figure><p>So this concludes the generation and usage of MeshGradient.</p><p>You can further play by altering the point values and background.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Qovr5Di-ppeRZznOck1lhw.gif" /></figure><p>source:- <a href="https://youtu.be/alhFwkbsxrs?si=lHXWGrenrq3cJby0">https://youtu.be/alhFwkbsxrs?si=lHXWGrenrq3cJby0</a></p><p>If you want to try my other articles</p><ul><li><a href="https://medium.com/@vishwasng/list/swift-data-a-unread-story-943d9c0304ee">Swift-CoreData</a></li><li><a href="https://medium.com/@vishwasng/list/task-and-taskgroup-47374c48e8a7">Swift-Tasks</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5894cf38fc7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobilepeople/crafting-stunning-uis-with-swiftui-mesh-gradients-d5894cf38fc7">Crafting Stunning UIs with SwiftUI: Mesh Gradients</a> was originally published in <a href="https://medium.com/mobilepeople">MobilePeople</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI :- Other Views]]></title>
            <link>https://medium.com/mobilepeople/swiftui-other-views-2c5649a45b4a?source=rss-213d9cabe71d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c5649a45b4a</guid>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[application-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Vishwas Ng]]></dc:creator>
            <pubDate>Wed, 15 Jan 2025 12:18:50 GMT</pubDate>
            <atom:updated>2025-02-05T10:02:07.647Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>SwiftUI :- Other Views</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dH5MryXF6w2JgAI7uNzfHA.png" /></figure><p>Hi when you start learning swiftUI you might have come across a lot of views like</p><ul><li>VStack, HStack, ZStack, ScrollView, Grid ……etc</li><li>Also maybe GeometryReader, Lazy(V,H,Z) Stack.</li></ul><p>Here I am trying to explore some Views that are rarely used in general. (If you are into swiftUI so deep you might already know these)</p><h3><strong>AnyLayout</strong></h3><p><a href="https://developer.apple.com/documentation/swiftui/anylayout">AnyLayout</a> comes in handy when you want to switch between HStack and VStack dynamically during run time</p><pre>struct AnyLayoutView: View {<br>    @State var dynamicLayout = true<br>    var body: some View {<br>        VStack(spacing:50) {<br>            let layout = dynamicLayout ? AnyLayout(HStackLayout()) : AnyLayout(VStackLayout())<br>            layout {<br>                Text(/*@START_MENU_TOKEN@*/&quot;Hello, World!&quot;/*@END_MENU_TOKEN@*/)<br>                    .modifier(CustomModifer())<br>                Text(&quot;This is Custom layout&quot;)<br>                    .font(.title)<br>                    .foregroundStyle(Color.teal)<br>            }<br>            <br>            Button(&quot;Toggle Layout&quot;) {<br>                dynamicLayout.toggle()<br>            }<br>        }<br>    }<br>}</pre><p>The condition of the switch doesn&#39;t have to be bool with a button, it can be anything like</p><ul><li>Device orientation (Landscape/Portrait)</li><li>Text Size for accessibility (XXL, XL)</li><li>based on count etc</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*8pgCYHa8a0AVccq1PKhsWg.gif" /></figure><h3><strong>ViewThatFits</strong></h3><p><a href="https://developer.apple.com/documentation/swiftui/viewthatfits">ViewThatFits</a> can be used where you need to render different Views based on the best fit within the available device frame.</p><p>This is convenient if you customize the view based on screen size.</p><p>ViewThatFits always</p><ul><li>Start checking from first view and so on</li><li>render the first View that fits the container</li><li>If none fits it render the last view</li></ul><h4>Tips</h4><ul><li>Start from highest view to lowest (See code Example)</li></ul><pre>struct ViewThatFitExample: View {<br>    var body: some View {<br>        ViewThatFits {<br>            RoundedRectangle(cornerRadius: 15)<br>                .fill(Color.orange)<br>                .padding(10)<br>                .frame(width: 300, height: 1000)<br>            <br>            RoundedRectangle(cornerRadius: 15)<br>                .fill(Color.red)<br>                .padding(10)<br>                .frame(width: 300, height: 700)<br>            <br>            RoundedRectangle(cornerRadius: 15)<br>                .fill(Color.blue)<br>                .padding(10)<br>                .frame(width: 300, height: 300)<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*dJc8O9k-ca6juLMrd324Pw.gif" /></figure><h3>ContentUnavailableView</h3><p><a href="https://developer.apple.com/documentation/swiftui/contentunavailableview">ContentUnavailableView</a> can be used to design placeholderViews or when content is unavailable (as the name itself suggests), such as</p><ul><li>When the list/table is empty</li><li>The network lost the error view</li><li>generic error with in-app</li><li>or like tutorial View before content loading</li></ul><ol><li><strong><em>Basic Unavailable View</em></strong></li></ol><pre>struct ContentViewBasic: View {<br>    @State var isContentAvailable = false<br>    var sampleData: [String] = [&quot;Available content one&quot;, &quot;Available content two&quot;, &quot;Available content three&quot;]<br>    @State var contentData : [String] = [&quot;Available content one&quot;, &quot;Available content two&quot;, &quot;Available content three&quot;]<br>    <br>    <br>    var body: some View {<br>        NavigationStack {<br>            ForEach(contentData, id: \.self) { contact in<br>                Text(contact)<br>            }<br>            .navigationTitle(&quot;Some View&quot;)<br>            .padding(10)<br>            .navigationViewStyle(.columns)<br>            <br>        }.overlay {<br>            if isContentAvaliable {<br>                getUnavailableContent()<br>            }<br>        }<br>        <br>        Button(action: {<br>            contentData = isContentAvaliable ? sampleData : []<br>            isContentAvaliable.toggle()<br>        }, label: {<br>            Text(!isContentAvaliable ? &quot;Switch Content to zero&quot; : &quot;Add Content&quot;)<br>                .foregroundColor(.white)<br>                .frame(width: 200, height: 40)<br>                .background(Color.green)<br>                .cornerRadius(15)<br>                .padding()<br>        })<br>        .frame(alignment: .bottom)<br>        <br>    }<br>    <br>    @ViewBuilder func getUnavailableContent() -&gt; some View {<br>        ContentUnavailableView {<br>            Image(systemName: &quot;text.page.slash&quot;)<br>                .font(.largeTitle)<br>                .foregroundStyle(.red)<br>                .symbolEffect(.wiggle.clockwise.wholeSymbol, options: .repeating)<br>            Text(&quot;No content here&quot;)<br>        }<br>    }<br>}</pre><p>in the above code, you can see that ‘getUnavailableContent()’ is called in an overlay of the list rendered only if the List is empty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*osnf9o6yKtHjTtJSnwBrBQ.gif" /></figure><p><strong><em>2. Content Unavailable View with action</em></strong></p><p>If it&#39;s just a view of what they use, hence it comes with a few extra inbuilt modifiers, like adding action to the content.</p><p>Just replace the function “getUnavailableContent() ”in the above-given code block with the below function, you can have an extra action button without any additional custom work.</p><pre>@ViewBuilder func getUnavailableContent() -&gt; some View {<br>       ContentUnavailableView(label: {<br>            Text(&quot;Fetching Failed&quot;)<br>                .font(.largeTitle)<br>                .fontWeight(.bold)<br>        }, description: {<br>            Image(systemName: &quot;text.page.slash&quot;)<br>                .font(.largeTitle)<br>                .foregroundStyle(.red)<br>                .symbolEffect(.wiggle.clockwise.wholeSymbol, options: .repeating)<br>                .padding(50)<br>            Text(&quot;No content here&quot;)<br>                .font(.title2)<br>        }, actions: {<br>            HStack(spacing: 24) {<br>                Button(&quot;Refresh&quot;, role: .cancel, action: {})<br>                Button (&quot;Go Back&quot;, role: .destructive, action: {})<br>                    .buttonStyle(.borderedProminent)<br>            }<br>            .fixedSize()<br>            .controlSize(.regular)<br>        })<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*FE0mtE3XmuS1CmuqhkxSmA.gif" /></figure><p>3. <strong><em>Content Unavailable View with paging</em></strong></p><p>As I mentioned earlier, this can also used with paging a tutorial view or 1 or more instruction views like onboarding or something like that.</p><pre>struct ContentViewPaging: View {<br>    <br>    var body: some View {<br>        getUnavailableContent()<br>    }<br>    <br>    @ViewBuilder func getUnavailableContent() -&gt; some View {<br>        TabView {<br>            ContentUnavailableView {<br>                Image(systemName: &quot;bonjour&quot;)<br>                    .font(.largeTitle)<br>                    .foregroundStyle(.blue)<br>                    .symbolEffect(.rotate.clockwise.wholeSymbol, options: .repeating)<br>                    .frame(width: 100, height: 100)<br>                    .padding()<br>                Text(&quot;Welcome to our app&quot;)<br>                    .font(.largeTitle)<br>                    .fontWeight(.bold)<br>            }<br>            ContentUnavailableView {<br>                Image(systemName: &quot;indianrupeesign.ring.dashed&quot;)<br>                    .font(.largeTitle)<br>                    .foregroundStyle(.pink)<br>                    .symbolEffect(.rotate.clockwise.wholeSymbol, options: .repeating)<br>                    .frame(width: 100, height: 100)<br>                    .padding()<br>                Text(&quot;Continue with SignUp&quot;)<br>                    .font(.largeTitle)<br>                    .fontWeight(.bold)<br>            }<br>            ContentUnavailableView {<br>                Image(systemName: &quot;apple.logo&quot;)<br>                    .font(.largeTitle)<br>                    .foregroundStyle(.green)<br>                    .symbolEffect(.wiggle.clockwise.wholeSymbol, options: .repeating)<br>                    .padding()<br>                Text(&quot;If already registered, SignIn&quot;)<br>                    .font(.largeTitle)<br>                    .fontWeight(.bold)<br>            }<br>        }<br>        .tabViewStyle(.page)<br>        .indexViewStyle(.page(backgroundDisplayMode: .always))<br>    }<br>}</pre><p>In the above code content view is used within paging style.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*P_0mxrIiJ61d1qN1kHw_bg.gif" /></figure><p>You can customize any view, but using a Content Unavailable View offers specific advantages. It provides a user-friendly way to inform users when content is not available while maintaining a consistent and polished interface. This approach enhances user experience by clearly communicating the absence of content and can encourage users to take alternative actions, such as refreshing or navigating elsewhere.</p><p>It helps in</p><ul><li>Fast-tracking your code/development</li><li>you do not need to worry about rendering in different sizes</li><li>comes with default actions</li></ul><p>I hope you discovered something new or rekindled your knowledge of familiar concepts!</p><p>If you’re an iOS developer looking to explore SwiftData, consider <a href="https://medium.com/@vishwasng/list/swift-data-a-unread-story-943d9c0304ee">this</a> curated reading list to enhance your knowledge and skills.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c5649a45b4a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobilepeople/swiftui-other-views-2c5649a45b4a">SwiftUI :- Other Views</a> was originally published in <a href="https://medium.com/mobilepeople">MobilePeople</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftData:- Query Master]]></title>
            <link>https://medium.com/mobilepeople/swiftdata-query-master-d0b5eded4c0f?source=rss-213d9cabe71d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0b5eded4c0f</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftdata]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[Vishwas Ng]]></dc:creator>
            <pubDate>Mon, 09 Sep 2024 12:30:06 GMT</pubDate>
            <atom:updated>2024-09-12T10:00:56.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*29Njx6ViAINCUbwiR2s8mw.png" /></figure><p>You learned about mocking the data and seeing the updated view from the <a href="https://medium.com/mobilepeople/swiftdata-the-mocking-world-de324d1ba527">previous article</a>. Now let&#39;s move on to a more detailed operation. You need to run the app to have a better experience.</p><h4><strong>What is Query?</strong></h4><p>In programming, a query requests data from a database or a command to act on data.</p><p>In this article, you are going to learn about two important factors of Querying</p><ul><li>Sorting</li><li>Filtering</li></ul><h4>Sorting</h4><p>so, let&#39;s look back at the code</p><pre>import SwiftUI<br>import SwiftData<br><br>struct CountryScreen: View {<br>    <br>    @Environment(\.modelContext) private var lmodelContext<br>    <br>    let country = [&quot;India&quot;, &quot;Afghanistan&quot;, &quot;Korea&quot;, &quot;Zimbabwe&quot;, &quot;USA&quot;, &quot;Nepal&quot;, &quot;Australia&quot;]<br>    let state = [&quot;Karnataka&quot;,&quot;Kabul&quot;, &quot;Seoul&quot;, &quot;Harare&quot;, &quot;Texas&quot;, &quot;Katmandu&quot;, &quot;Perth&quot;]<br>    let flag = [&quot;in&quot;,&quot;af&quot;, &quot;kr&quot;, &quot;zw&quot;, &quot;us&quot;, &quot;np&quot;, &quot;au&quot;]<br>    <br>    @Query(sort: \Country.country, order:.forward) var countryData: [Country]<br>    <br>    var body: some View {<br>        NavigationStack {<br>            List(countryData) { ldata in<br>                NavigationLink {<br>                    Text(ldata.country)<br>                } label: {<br>                    listView(ldata: ldata)<br>                }<br>            }.listStyle(.sidebar)<br>                .listRowBackground(Color.clear)<br>                .listRowInsets(.none)<br>            Button(&quot;Add Country&quot;) {<br>                let num = Int.random(in: 0..&lt;7)<br>                let country = Country(country: country[num], state: state[num], flag: flag[num])<br>                lmodelContext.insert(country)<br>            }<br>            .navigationTitle(&quot;Countries&quot;)<br>            .toolbar {<br>                Button(&quot;&quot;, systemImage: orderAscending ? &quot;arrow.down&quot; : &quot;arrow.up&quot;) {<br>                    orderAscending.toggle()<br>                }<br>            }<br>        }<br>    }<br>    <br>    func listView(ldata:Country) -&gt; some View{<br>        return  HStack(spacing:25) {<br>            Image(uiImage: ldata.viewCountryImage)<br>                .resizable()<br>                .frame(width:40, height: 40)<br>            VStack(alignment: .leading) {<br>                Text(ldata.country)<br>                    .font(.title2)<br>                Text(ldata.state)<br>                    .font(.title3)<br>            }<br>            Spacer()<br>        }<br>    }<br>}<br><br>#Preview {<br>    CountryScreen()<br>}</pre><p>and observe the code</p><pre>@Query(sort: \Country.country, order:.forward) var countryData: [Country]</pre><p>this yields below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*FV5G-6MX5LwmZ0wFMWPZAA.png" /></figure><p>If you observe the above list, it&#39;s ordered alphabetically. Now let&#39;s change the query to the basic one as below</p><pre>@Query var countryData: [Country]</pre><p>it yields as a screenshot below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*gIWfPcLXx1svNq_9qo6UtQ.png" /></figure><p>This is also based on the query result without any sorting.</p><h4>Sorting Summary</h4><ul><li>Sorting can be done based on any property within the observable model</li><li>The simple way of specifying is the parameter you need to sort with</li></ul><pre>@Query(sort: \ModelType.propertyName) var query_Result: [Model Type]</pre><ul><li>This will help to sort the queried result</li><li>Only comparables can be sorted</li><li>The sorting properties cannot be applied to the computed property of the Model</li><li>All sort happens by default as ascending, but you need to specify if your requirement is otherwise</li></ul><pre>@Query(sort: ModelType.propertyName, order: reverse) var query_Result: [Model Type]</pre><h4>Filtering</h4><p>so let&#39;s deal with filtering now replace the query line with the below</p><pre>@Query(filter: #Predicate&lt;Country&gt; {$0.country == &quot;India&quot;})  var countryData: [Country]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*2I9sW9vf00q3kEk_V2krCQ.png" /></figure><p>As you can see, you see only <strong>India</strong> on the list because you are filtering based on it.</p><ul><li>Filter uses predicate API to do the filtering</li></ul><pre> @Query (filter: #Predicate&lt;Model Type&gt; (value in value.property = &quot;valueData&quot; )) private var filter_ Result: [Mode/Type]</pre><ul><li>The filter can also use shorthand arguments and trailing closure</li></ul><p>So, from the above explanation, you know how basic query works.</p><h3><strong>Updating Data</strong></h3><p>Let&#39;s see how we can update the existing data. Before that, let&#39;s see <a href="https://developer.apple.com/documentation/swiftui/bindable">@Bindable</a> in brief</p><ul><li>Use to create bindings to mutable properties of a data model object that conforms to the Observable protocol.</li><li>It can also be used in conjunction with the Environment variable.</li></ul><p>Basically, in simple words Bindable is used to have 2 way binding to the data so update on one side do update on other places too.</p><p>Lets code</p><p>Create a new swiftUI file with the name “<em>ListView.swift</em>” and add the below code</p><pre>import SwiftUI<br>import SwiftData<br><br>struct ListView: View {<br>    @Bindable var cu: Country<br><br>    var body: some View {<br>        VStack(alignment: .center, spacing: 50){<br>            Image(uiImage: cu.viewCountryImage)<br>                .resizable()<br>                .frame(width: 150, height: 150)<br>                .cornerRadius(3.0)<br>            VStack(alignment:.leading) {<br>                Text(cu.country)<br>                    .font(.largeTitle.bold())<br>                Text(cu.state)<br>                    .font(.headline.italic())<br>            }<br>        }.padding()<br>            .ignoresSafeArea()<br>            .onTapGesture(perform: {<br>                cu.state = &quot;\(cu.state) - visited&quot;<br>            })<br>    }<br>}<br><br>#Preview {<br>    let container = try! ModelContainer(for: Country.self,                                        configurations: ModelConfiguration(isStoredInMemoryOnly: true))<br>    let country = Country(country: &quot;India&quot;, state: &quot;Karnataka&quot;, flag: &quot;in&quot;)<br>    container.mainContext.insert(country)<br>    return ListView(cu: country)<br>}</pre><p>And replace the code</p><pre>Text(ldata.country)</pre><p>with</p><pre>ListView(cu: ldata)<br>   .modifier(CustomBackgroundModifier())</pre><p>in file CountryScreen.swift, so when you tap on the list you see as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*ZbKgVUL0WUWsiIlo-OsdTQ.png" /></figure><p>In Code, if you observe, we have a code</p><pre>@Bindable var cu: Country</pre><p>which helps in 2 way binding. When you tap on the image, we are updating the database as viewed</p><pre>.onTapGesture(perform: {<br>                cu.state = &quot;\(cu.state) - visited&quot;<br>            })</pre><p>to do this, you are not required to use any context exclusively as it is bindable from the previous screen and also gets updated on the main screen too</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*nW4XDnfxgqtGrbVlPB4K8Q.png" /></figure><p>From the above screenshot you can see the state value is updates that you performed in different screens.</p><h3>Delegating Data</h3><p>So till now in this series you have learnt about setting up swiftData and how to create/update data into SwiftData let&#39;s learn how you can delete one.</p><p>add the below code to the list in the “<em>CountryScreen.swift</em>”</p><pre>.onDelete(perform: { indexSet in<br>                        lmodelContext.delete(countryData[indexSet.first ?? 1])<br>                    })</pre><p>and the final code should look like below</p><pre><br>    var body: some View {<br>        NavigationStack {<br>            List() {<br>                Section(&quot;Sorting&quot;) {<br>                    ForEach(countryData, id: \.self) { ldata in<br>                        NavigationLink {<br>                            ListView(cu: ldata)<br>                                .modifier(CustomBackgroundModifier())<br>                        } label: {<br>                            listView(ldata: ldata)<br>                        }<br>                    }.onDelete(perform: { indexSet in<br>                        lmodelContext.delete(countryData[indexSet.first ?? 1])<br>                    })<br>                }<br>                Section(&quot;Filtering&quot;) {<br>                    ForEach(filteredCountryData, id: \.self) { ldata in<br>                        NavigationLink {<br>                            ListView(cu: ldata)<br>                                .modifier(CustomBackgroundModifier())<br>                        } label: {<br>                            listView(ldata: ldata)<br>                        }<br>                    }<br>                }<br>            }.listStyle(.grouped)<br>                .listRowBackground(Color.clear)<br>                .listRowInsets(.none)<br>            Button(&quot;Add Country&quot;) {<br>                let num = Int.random(in: 0..&lt;7)<br>                print(num)<br>                let country = Country(country: country[num], state: state[num], flag: flag[num])<br>                lmodelContext.insert(country)<br>            }<br>            .navigationTitle(&quot;Countries&quot;)<br>            .toolbar {<br>                Button(&quot;&quot;, systemImage: orderAscending ? &quot;arrow.down&quot; : &quot;arrow.up&quot;) {<br>                    orderAscending.toggle()<br>                }<br>            }<br>        }<br>    }</pre><p>Now you can delete data, if you observe the code inside the delete block you can see we are still using <em>model context</em> to remove data as same as inserting the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*JCrgX3vRRKmsc1CHzvfYPA.png" /></figure><p><strong>Summary</strong></p><ul><li>This article covers querying any items from the store.</li><li>Explained in detail how to Sort and Filter during a query.</li><li>Also covering update and Delete functionality.</li></ul><h4><a href="https://medium.com/@vishwasng/list/swift-data-a-unread-story-943d9c0304ee">Series Summary</a></h4><ul><li>In this series, we learned the basics of SwiftData.</li><li>Different components are involved in SwiftData.</li><li>How to set a project and use different components.</li><li>Covered all CRUD operations.</li></ul><h4>GitHub repo</h4><p><a href="https://github.com/vishw33/SwiftData/blob/main/README.md">SwiftData/README.md at main · vishw33/SwiftData</a></p><p><em>The whole reading list can be accessed from below link</em></p><p><a href="https://medium.com/@vishwasng/list/swift-data-a-unread-story-943d9c0304ee">https://medium.com/@vishwasng/list/swift-data-a-unread-story-943d9c0304ee</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0b5eded4c0f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobilepeople/swiftdata-query-master-d0b5eded4c0f">SwiftData:- Query Master</a> was originally published in <a href="https://medium.com/mobilepeople">MobilePeople</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftData:- The Mocking world]]></title>
            <link>https://medium.com/mobilepeople/swiftdata-the-mocking-world-de324d1ba527?source=rss-213d9cabe71d------2</link>
            <guid isPermaLink="false">https://medium.com/p/de324d1ba527</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftdata]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Vishwas Ng]]></dc:creator>
            <pubDate>Mon, 02 Sep 2024 12:43:36 GMT</pubDate>
            <atom:updated>2024-09-09T12:46:42.207Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3bfsxt-lj20iZydgir6mrQ.png" /></figure><p>Welcome back to the SwiftData series; in the <a href="https://medium.com/mobilepeople/swiftdata-the-project-setup-ece662cb5042">last article,</a> I told you we would be looking into Querying the data, that if you have observed from the project setup article, if you try to preview the view, it might break down and doesn&#39;t work. If you think you did something wrong, no, you are not. Let&#39;s fix it now and learn more about Mock.</p><h4>lets review code</h4><pre>#Preview {<br>    CountryScreen()<br>}</pre><p>The container you set will be w.r.t to the app container, the preview cannot use the same container. so the preview needs the container to work. so the solution is to set the container to the preview</p><pre>#Preview {<br>    CountryScreen()<br>    .modelContainer(for:Country.self)<br>}</pre><p>So now this sets the container to the preview; this fixes the problem: YES and NO</p><h4>why YES?</h4><ul><li>Yes, the preview works.</li><li>You can add it and see the previewed data.</li></ul><h4>why NO?</h4><ul><li>Now your app and preview share the same container</li><li>the data you used for the preview doesn&#39;t need to persist.</li><li>also, the persistent data might be compromised.</li></ul><h4>Another problem</h4><ul><li>is that there will be no initial data</li><li>Different variants of data(because data drive UI) might not be available.</li></ul><h4>So, fix all problems here comes the Mocking</h4><p>Before mocking, we still need the container to mock the data and add data to the container, so to avoid conflict, we do the below steps</p><ul><li>create custom container</li><li>Make sure the container data that is used for the preview only (no persistence)</li><li>Add the mock data to the container, let&#39;s do it</li></ul><pre>#Preview {<br>    let container = try! ModelContainer(for: Country.self,<br>                                        configurations: ModelConfiguration(isStoredInMemoryOnly: true))<br>    let country = Country(country: &quot;India&quot;,<br>                          state: &quot;Karnataka&quot;,<br>                          flag: &quot;in&quot;)<br>    container.mainContext.insert(country)<br>    return CountryScreen()<br>        .modelContainer(container)<br>    <br>}</pre><p>From the above code, it is evident that we created the container and added the data to mock in the preview. it should somehow look like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4JgjSY84Aywe6EOqm-cF8g.png" /></figure><p>So now you have data to see the preview without adding/manipulating the actual code. So, I can verify the UI rendering without any hassle.</p><h4>Lets Improvise now</h4><ul><li>in the above preview code, if you try to add more data, the code becomes more complex(multiple schemas, etc).</li><li>code resides in your main view making it look more lengthy code.</li><li>also, there might be an N number of previews, and all placed in each view are a bit hard to track.</li><li>So it&#39;s better to separate the Mock from the actual production code.</li><li>make sure all code is available in one place for easy access and maintenance.</li></ul><p>For the above reason mentioned the “<strong>Extensions</strong>” come to our rescue</p><pre>extension Country {<br>    @MainActor<br>    static var preview:ModelContainer {<br>        let container = try! ModelContainer(for: Country.self, configurations: ModelConfiguration(isStoredInMemoryOnly: true))<br>        container.mainContext.insert(Country(country: &quot;India&quot;, state: &quot;Karnataka&quot;, flag: &quot;in&quot;))<br>        container.mainContext.insert(Country(country: &quot;Zimbabwe&quot;, state: &quot;Harare&quot;, flag: &quot;zw&quot;))<br>        return container<br>    }<br>}</pre><p>Create a new Swift file in your project and enter the above code or you can use your existing model file for the same.</p><p>with the help of extension and static variables, we can reduce our preview code as below</p><pre>#Preview {<br>    CountryScreen()<br>    .modelContainer(Country.preview)<br>}</pre><p>This gives a clean look to the preview and can add any view logic required for the preview and isolate mock data to completely different files.</p><p>This still yields the same result as before</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CnacuRK6Pl_YcGC9heeCSg.png" /></figure><h4>Bonus</h4><ul><li>you can move extension files and assets (if any) w.r.t. preview to the “<strong><em>preview content”</em></strong> folder</li><li>for more info about “<strong><em>preview content” </em></strong>refer <a href="https://developer.apple.com/videos/play/wwdc2020/10149">WWDC video</a>.</li></ul><h4>Summary</h4><p>In this article, you came to know how to fix the preview issue, create a custom container, add the mock data, and customise it for better readability.</p><p>In the next article, we continue with the Query in SwiftData.</p><p><em>Whole reading list can be accessed from below link</em></p><p><a href="https://medium.com/@vishwasng/list/swift-data-a-unread-story-943d9c0304ee">https://medium.com/@vishwasng/list/swift-data-a-unread-story-943d9c0304ee</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de324d1ba527" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobilepeople/swiftdata-the-mocking-world-de324d1ba527">SwiftData:- The Mocking world</a> was originally published in <a href="https://medium.com/mobilepeople">MobilePeople</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftData:- The project setup]]></title>
            <link>https://medium.com/mobilepeople/swiftdata-the-project-setup-ece662cb5042?source=rss-213d9cabe71d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ece662cb5042</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swiftdata]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Vishwas Ng]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 12:20:42 GMT</pubDate>
            <atom:updated>2024-09-09T12:45:59.010Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7CrXJB24h-9NCHfVgEMSBQ.png" /></figure><p>This is the third part of the swiftData series. If you still need to read the previous part please refer <a href="https://medium.com/@vishwasng/list/swift-data-a-unread-story-943d9c0304ee">here</a>.</p><p>In previous articles, we learned about SwiftData and its components. Let&#39;s try to set up the project and all the elements needed to give it a try in SwiftData.</p><h4>Let&#39;s start with the basic setup</h4><p>The first step would be creating a new project</p><p>Open Xcode -&gt; File -&gt; New Project</p><p>Select iOS -&gt; App -&gt; Next (Until here, it is pretty much straightforward)</p><p>next give project Name -&gt; bundle ID -&gt; SwiftUI -&gt; and storage select none</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_wv8WGgHyevuKo_rDo6Hwg.png" /></figure><p>Here we are selecting none because we will set the swiftData code ourselves in the project so that you will get the hang of all the previous explanations.</p><p>Of course, you get boilerPlate code set with swiftData selected as storage, instead of analysing code we create our own.</p><h4>Setting container</h4><pre>import SwiftUI<br>import SwiftData<br><br>@main<br>struct Country_ListApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            CountryScreen()<br>                .modelContainer(for:Country.self)<br>        }<br>    }<br>}</pre><p>Once you create a new project you get <em>contentView.swift</em> and it will be the entry point for your project. you can delete that file and add the above.( <em>its understand that by now you know how swiftUI app entry works</em>)</p><p>Let us break the code, to use the swiftData “<strong>import SwiftData</strong>” header is used. If you remember my previous article you should have read about “<a href="https://medium.com/@vishwasng/swiftdata-the-beginning-ece011594272"><em>the container</em></a>”. Here we can set the container to the root of the application.</p><ul><li>you can set the container to any view and all the child views can access it.</li><li>you can set any number of containers to a view</li></ul><p><strong>Container Characteristics</strong></p><p><em>Adding multiple models:-</em></p><pre>@Model<br>class Time {<br>    var timeStamp:String<br>    <br>    init(timeStamp:String) {<br>        self.timeStamp = timeStamp<br>    }<br>}</pre><pre>@Model<br>class MDate {<br>    var dateStamp:String<br>    <br>    init(dateStamp:String) {<br>        self.dateStamp = dateStamp<br>    }<br>}</pre><p>Let&#39;s consider the above two models needed all over the app</p><p>you can add containers as shown below</p><p><strong>i) The Direct way,</strong></p><pre>var container = try! ModelContainer(for:Time.self, MDate.self)<br><br>var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>        }<br>        .modelContainer(container)<br>    }</pre><p>In the above code, you see if you need to add a container with all default parms you can simply do it as mentioned above</p><p><strong>ii) Setting Container Charastericts</strong></p><pre>let container = try! ModelContainer(for: Schema([Time.self,<br>                                                  MDate.self]),<br>                                     configurations: ModelConfiguration(isStoredInMemoryOnly: true),<br>                                     ModelConfiguration(allowsSave:true))<br>var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>        }<br>        .modelContainer(container)<br>    }</pre><p>But if you have to specify the schema with a common ModelConfiguration, you can do as shown in the above code and set the container.</p><p><strong>iii) setting individual</strong> <strong>Charastericts</strong></p><pre>let config1 = ModelConfiguration(for:Time.self,<br>                                     isStoredInMemoryOnly: true)<br>let config2 = ModelConfiguration(for:MDate.self,<br>                                     isStoredInMemoryOnly: false)<br>let container = try! ModelContainer(for: Time.self, MDate.self, <br>                                         configurations: config1, config2)<br><br>var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>        }<br>        .modelContainer(container)<br>    }</pre><p>But in the realistic world, each schema might have its configuration so the example in the above code.</p><h4>Setting Context</h4><p>Now coming back to the project create a new screen</p><p>File -&gt; New -&gt; File -&gt; SwiftUI View</p><p>Name it “<strong><em>CountryScreen.swift</em></strong>”, mean while download and keep flag icons and add to the asset ( <a href="https://flagpedia.net/download/icons#google_vignette">flag icon</a>)</p><pre>import SwiftUI<br>import SwiftData<br><br>struct CountryScreen: View {<br>    <br>    @Environment(\.modelContext) private var lmodelContext<br>    <br>    let country = [&quot;India&quot;, &quot;Afghanistan&quot;, &quot;Korea&quot;, &quot;Zimbabwe&quot;, &quot;USA&quot;, &quot;Nepal&quot;, &quot;Australia&quot;]<br>    let state = [&quot;Karnataka&quot;,&quot;Kabul&quot;, &quot;Seoul&quot;, &quot;Harare&quot;, &quot;Texas&quot;, &quot;Katmandu&quot;, &quot;Perth&quot;]<br>    let flag = [&quot;in&quot;,&quot;af&quot;, &quot;kr&quot;, &quot;zw&quot;, &quot;us&quot;, &quot;np&quot;, &quot;au&quot;]<br>    <br>    @Query(sort: \Country.country, order:.forward) var countryData: [Country]<br>    <br>    var body: some View {<br>        NavigationStack {<br>            List(countryData) { ldata in<br>                NavigationLink {<br>                    Text(ldata.country)<br>                } label: {<br>                    listView(ldata: ldata)<br>                }<br>            }.listStyle(.sidebar)<br>                .listRowBackground(Color.clear)<br>                .listRowInsets(.none)<br>            Button(&quot;Add Country&quot;) {<br>                let num = Int.random(in: 0..&lt;7)<br>                let country = Country(country: country[num], state: state[num], flag: flag[num])<br>                lmodelContext.insert(country)<br>            }<br>            .navigationTitle(&quot;Countries&quot;)<br>            .toolbar {<br>                Button(&quot;&quot;, systemImage: orderAscending ? &quot;arrow.down&quot; : &quot;arrow.up&quot;) {<br>                    orderAscending.toggle()<br>                }<br>            }<br>        }<br>    }<br>    <br>    func listView(ldata:Country) -&gt; some View{<br>        return  HStack(spacing:25) {<br>            Image(uiImage: ldata.viewCountryImage)<br>                .resizable()<br>                .frame(width:40, height: 40)<br>            VStack(alignment: .leading) {<br>                Text(ldata.country)<br>                    .font(.title2)<br>                Text(ldata.state)<br>                    .font(.title3)<br>            }<br>            Spacer()<br>        }<br>    }<br>}<br><br>#Preview {<br>    CountryScreen()<br>}</pre><p>Take a look at the “<em>lmodelContext</em>” in the above code. You guys know about context by now.</p><p>As you know if you want to insert the data or edit it you need the Context, no matter how complex the internal working of the context outside API exposure is simple, check the action of the “<em>Add country button</em>”</p><pre>let num = Int.random(in: 0..&lt;7)<br>let country = Country(country: country[num], state: state[num], flag: flag[num])<br>lmodelContext.insert(country)</pre><p>The above code creates country data and adds it to the container for later retrieval/Update.</p><p>This is how simple CRUD operation can be on SwiftData. Don&#39;t worry about the other code I will cover in the following article.</p><h4>Summary</h4><p>Now, you have the knowledge to do the basic swiftData setup and add data to the container. In the next article, we will see how Query works and how to build a View with Query data.</p><p><em>(</em><strong><em>P.S If you followed the above steps and your preview is breaking, don&#39;t worry, use the simulator for now. I will explain how to fix it later</em></strong><em>)</em></p><p><em>Whole reading list can be accessed from below link</em></p><p><a href="https://medium.com/@vishwasng/list/swift-data-a-unread-story-943d9c0304ee">https://medium.com/@vishwasng/list/swift-data-a-unread-story-943d9c0304ee</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ece662cb5042" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobilepeople/swiftdata-the-project-setup-ece662cb5042">SwiftData:- The project setup</a> was originally published in <a href="https://medium.com/mobilepeople">MobilePeople</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftData:- The Beginning]]></title>
            <link>https://medium.com/mobilepeople/swiftdata-the-beginning-ece011594272?source=rss-213d9cabe71d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ece011594272</guid>
            <category><![CDATA[swiftdata]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Vishwas Ng]]></dc:creator>
            <pubDate>Mon, 19 Aug 2024 13:37:23 GMT</pubDate>
            <atom:updated>2024-09-09T12:42:21.424Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWJmdPI4Ai9vzHZwcyS0Wg.png" /></figure><p>This is the second part of the series(<a href="https://medium.com/@vishwasng/swiftdata-the-introduction-cc036aab008b">first part</a>), In the last article we came to know the main components of the SwiftData flow let&#39;s go into detail about each</p><h4><a href="https://developer.apple.com/documentation/swiftdata/model()">Model</a></h4><p>Let&#39;s see the example of the model</p><pre>@Model<br>class Country {<br>    var country:String<br>    var state:String<br>    var flag:String<br>    <br>    init(country: String, state: String, flag: String) {<br>        self.country = country<br>        self.state = state<br>        self.flag = flag<br>    }<br>}</pre><p>As I said, the Model is the same as any you defined before for Codable. But here, it is attributed to the @Model property wrapper and no decodeKeys. so let&#39;s see in detail what all contribute to the swiftData model</p><ul><li>It should always start with the @Model property wrapper, which tells the app to create a persistence container for that model.</li><li>It should always be a “C<em>lass</em>” but can contain struct and enum within a class as a variable.</li><li>It should always have an initializer and can have a default value.</li><li>Why all these are important is because the model will be built in Observer.</li><li>The model can have any primitive data as its variable along with struct and Enum, as mentioned above.</li><li>Automatically confirms an identifier protocol.</li></ul><h4><a href="https://developer.apple.com/documentation/swiftdata/modelcontainer">Container</a></h4><p>Let&#39;s see how we can set the container first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eH33IZAkLb6IWAKqTDti6Q.png" /></figure><p>You can set the container as shown in line 16. You will then know where else you can set the container and how to access it.</p><ul><li>by setting the container, you make sure the app sets permanent storage.</li><li>It helps to set the data with default values.</li><li>It helps send data to the Context.</li><li>The app can have any number of containers.</li></ul><h4><a href="https://developer.apple.com/documentation/swiftdata/modelcontext">Context</a></h4><p>We have seen what the is model, and The container lets us know more about the Context.</p><pre>@Environment(\.modelContext) private var lmodelContext</pre><p>The above code simplifies how the context is loaded into Environment/View. The context comes into play when you want to manipulate the data before loading/Saving it into memory.</p><p>The context acts as a tool for manipulating the data. The code below shows how the data is inserted into memory.</p><pre> let country = Country(country: &quot;India&quot;, state: &quot;Karnataka&quot;, flag: &quot;in&quot;)<br> lmodelContext.insert(country)</pre><p>You don&#39;t need to specify a data type for the context because you get the type from the container, and swiftData is intelligent enough to know what data you are trying to insert.</p><h4><a href="https://developer.apple.com/documentation/swiftui/view">View</a></h4><p>This must be a simple one, the view is any simple swiftUI view</p><pre>var body: some View {<br>     ListView(country: ldata)<br>       .modifier(CustomBackgroundModifier())<br>}</pre><p>here “<em>ldata</em>” is Queried data, which you will learn later in this series.</p><h4>Summary</h4><p>So you know all the components in the Swift data, Understanding this is very important as all swiftData stuff revolves around these things ….</p><p>In the next article, we will learn about setting up a project and all the code examples mentioned in this article with details…</p><p><em>Whole reading list can be accessed from below link</em></p><p><a href="https://medium.com/@vishwasng/list/943d9c0304ee">Swift Data :- A unRead story</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ece011594272" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobilepeople/swiftdata-the-beginning-ece011594272">SwiftData:- The Beginning</a> was originally published in <a href="https://medium.com/mobilepeople">MobilePeople</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftData:- The Introduction]]></title>
            <link>https://medium.com/mobilepeople/swiftdata-the-introduction-cc036aab008b?source=rss-213d9cabe71d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc036aab008b</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swiftdata]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[core-data]]></category>
            <dc:creator><![CDATA[Vishwas Ng]]></dc:creator>
            <pubDate>Tue, 13 Aug 2024 13:39:28 GMT</pubDate>
            <atom:updated>2024-09-09T12:44:48.328Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SGqos-UyjoOlGWqEvo25pA.png" /></figure><p>Apple introduced Swift Data almost a year ago, as an additional to core data for the persistence of the data in iOS. Every year, Apple brings new and innovative things such as a new framework or improvements in existing frameworks (like swiftUI/Maps etc).</p><p><strong><em>I plan to introduce SwiftData in my series of articles(at least 7–8) in a simple way. You learn more in the upcoming articles.</em></strong></p><h4>What exactly is swiftData?</h4><p>SwiftData is a persistence data framework Apple introduced to store data within an application(container) on a device. It is more easy and reliable to use and also goes well with SwiftUI, unlike coreData which is based on Objective-C API.</p><p><strong><em>Here, I am not going to discuss SwiftData vs CoreData, or their similarities/differences this is dedicated to knowing SwiftData</em></strong></p><h4>How SwiftData work?</h4><figure><img alt="SwiftData workFlow" src="https://cdn-images-1.medium.com/max/591/1*5_BBVN6HMu3wmCIFl6wl2Q.jpeg" /><figcaption>SwiftData workflow</figcaption></figure><p>From the above picture, you see the 4 main parts of SwiftData.</p><ul><li>Model</li><li>Container</li><li>Context</li><li>View</li></ul><h4>Model</h4><p>The Model is the same as the codable Model you use regularly for phrasing which defines the data structure.</p><h4>Container</h4><p>When storing the data, you need a specified space on the device with a predetermined structure ready for storage. Hence that store space is called a container.</p><h4>Context</h4><p>The data must be stored in the container, but not all are stored and retrieved directly. You need a space where data can persist for different operations (CRUD) before being stored permanently in a to/from container. For this purpose, <em>Context</em> comes into the picture.</p><h4>View</h4><p>The View is a simple SwiftUI view where the user interacts. Here I am mentioning the SwiftUI view, which can also be used with UIKitViews.</p><p>This is the brief introduction I am going to give more details on these in the next blog (here) as I said at starting it&#39;s a series of articles.</p><h4>Summary</h4><p>The introduction gives the basic idea of the components involved in SwiftData, in the next part you learn more about each component and its characteristics.</p><p><em>Whole reading list can be accessed from below link</em></p><p><a href="https://medium.com/@vishwasng/list/swift-data-a-unread-story-943d9c0304ee">https://medium.com/@vishwasng/list/swift-data-a-unread-story-943d9c0304ee</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc036aab008b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobilepeople/swiftdata-the-introduction-cc036aab008b">SwiftData:- The Introduction</a> was originally published in <a href="https://medium.com/mobilepeople">MobilePeople</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>