<?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 Purva on Medium]]></title>
        <description><![CDATA[Stories by Purva on Medium]]></description>
        <link>https://medium.com/@purva.r12?source=rss-5140c140bdf5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8biCNMMNwsAp34392xtyBA.jpeg</url>
            <title>Stories by Purva on Medium</title>
            <link>https://medium.com/@purva.r12?source=rss-5140c140bdf5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 14:20:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@purva.r12/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[The New Reactive SwiftUI: A Practical Guide]]></title>
            <link>https://medium.com/@purva.r12/the-new-reactive-swiftui-a-practical-guide-ec4cec58adbe?source=rss-5140c140bdf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec4cec58adbe</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Purva]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 11:01:27 GMT</pubDate>
            <atom:updated>2026-03-25T11:01:27.902Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YLiXZdzKbsyfP4HPO1Ut2A.png" /></figure><p>Understanding @Observable, @Bindable, @Entry, and modern state management in iOS 17+</p><h3>Why Apple Introduced @Observable alongside Combine ?</h3><p>SwiftUI state management has always worked — but it rarely felt simple.<br>Between @StateObject, @ObservedObject, @EnvironmentObject, and @Published, even small features required careful decisions about ownership, lifecycle, and data flow.<br>More often than not, views updated more than they needed to.</p><p>With iOS 17, Apple introduced the <strong>Observation framework</strong> — a Swift-native, Combine-free approach to reactive state.</p><p>At the center of this shift is @Observable, a macro that doesn’t just reduce boilerplate—it changes how SwiftUI tracks and updates state altogether.</p><blockquote>💡 <strong>The key insight:</strong> The Observation framework doesn’t replace Combine — it replaces ObservableObject. Combine still lives on for everything it does best: async pipelines, networking streams, debounce, and timer publishers.</blockquote><p>Let’s say we have a simple profile model in a Combine-based SwiftUI app:</p><pre>import Combine<br><br>class ProfileViewModel: ObservableObject {<br>    @Published var name: String = &quot;&quot;<br>    @Published var age: Int = 0<br>    @Published var isLoading: Bool = false<br>}<br><br>struct ProfileView: View {<br>    @StateObject private var vm = ProfileViewModel()<br><br>    var body: some View {<br>        Text(vm.name) // re-renders if ANY @Published changes<br>       // BUT ALSO when age or isLoading changes<br>       // Even though this view never reads them<br>    }<br>}</pre><h3>@Observable Macro</h3><p>The <strong>@Observable</strong> macro is the star of the show. Add it to any class and the compiler quietly generates the entire observation infrastructure for you — no manual protocol conformance, <strong>no</strong> <strong>@Published</strong> scattered across every property. The real win is surgical re-rendering.</p><p>Previously, changing any<strong> @Published</strong> property notified every view watching that object even views that never used that property. Now SwiftUI tracks exactly which properties each view reads and only re-renders that specific view when those specific properties change. Nothing else wakes up.</p><h4><strong>Why This works</strong></h4><p>@Observable introduces fine-grained tracking at the property level.</p><p>When SwiftUI renders a view, it records exactly which properties are accessed during that render. Later, only changes to those specific properties trigger updates for that view.</p><p>This shifts SwiftUI from object-level updates to property-level updates — making re-rendering more precise and predictable.</p><p>Here’s what that looks like in practice:</p><pre>@Observable<br>final class ProfileViewModel {<br>    var name: String = &quot;&quot;      // automatically tracked<br>    var age: Int = 0           // automatically tracked<br>    var isLoading: Bool = false // automatically tracked<br><br>    @ObservationIgnored<br>    var sessionToken: String = &quot;&quot; // opt-out from tracking<br>}<br><br>struct ProfileView: View {<br>    @State private var vm = ProfileViewModel()<br><br>    var body: some View {<br>        Text(vm.name) // only &#39;name&#39; changes will trigger this view to update<br>    }<br>}</pre><blockquote><strong>@ObservationIgnored</strong> is your escape hatch. Use it for properties that change frequently (caches, tokens, internal flags) but should never trigger view updates.</blockquote><h3>Property Wrappers Simplified</h3><p>One of the most confusing parts of pre-iOS 17 SwiftUI was knowing which property wrapper to reach for. With Observation, Apple reduced this to three primary wrappers: @State, @Environment, and @Bindable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQxmLijO02zSwHOiqSgpWQ.png" /></figure><h4>@State — The Ownership Wrapper</h4><p>@State does two things when used with an @Observable class — it <strong>stores</strong> the instance across view redraws, and tells SwiftUI <em>&quot;this view is the source of truth, it created this model.&quot;</em></p><p>Think of it like this — someone has to <strong>own</strong> the ProfileViewModel. That someone is RootView. It creates it, it holds it, and it keeps it alive as long as it exists.</p><pre>struct RootView: View {<br>    @State private var vm = ProfileViewModel()<br><br>    var body: some View {<br>        ProfileView(vm: vm)  // pass without $ — no wrapper needed in child<br>    }<br>}<br><br>// Wrong — ProfileView should NOT own the model<br>// Someone else (RootView) already created it<br>struct ProfileView: View {<br>    @State private var vm = ProfileViewModel() // creates a SECOND instance!<br>}<br><br>// Correct — ProfileView just receives it<br>struct ProfileView: View {<br>    let vm: ProfileViewModel  // receives the ONE instance RootView owns<br>}</pre><blockquote><strong>Important rule — use </strong><strong>@State ONLY in the view that creates the model.</strong> Not in every view that uses it.</blockquote><h4>No Wrapper — Just Pass It</h4><p>This is the most surprising change from <em>iOS 17</em>. Before, every child view that received an ObservableObject had to declare @ObservedObject — otherwise SwiftUI wouldn&#39;t track it and the view would never update.</p><p>Now with @Observable, a plain let is enough. SwiftUI tracks property reads automatically, regardless of how the object arrived in the view.</p><p>Before iOS 17,</p><pre>class ProfileViewModel: ObservableObject {<br>    @Published var name: String = &quot;Adam&quot;<br>    @Published var followerCount: Int = 1200<br>}<br><br>// Parent — creates and OWNS the model<br>struct RootView: View {<br>    @StateObject private var vm = ProfileViewModel()<br>    // @StateObject = created once, never recreated<br><br>    var body: some View {<br>        ProfileView(vm: vm)  // passes down to child<br>    }<br>}<br><br>// Child — receives the model<br>struct ProfileView: View {<br>    @ObservedObject var vm: ProfileViewModel<br>    // Without @ObservedObject, Text(vm.name) would never update<br><br>    var body: some View {<br>        Text(vm.name)<br>        Text(&quot;\(vm.followerCount) followers&quot;)<br>    }<br>}</pre><p>after iOS 17+,</p><pre>@Observable<br>final class ProfileViewModel {<br>    var name: String = &quot;Adam&quot;<br>    var followerCount: Int = 1200<br>}<br><br>// Parent - creates and OWNS the model<br>struct RootView: View {<br>    @State private var vm = ProfileViewModel()<br>    // @State replaces @StateObject<br><br>    var body: some View {<br>        ProfileView(vm: vm)<br>    }<br>}<br><br>// Child - receives the model<br>struct ProfileView: View {<br>    let vm: ProfileViewModel<br>    // plain let - no wrapper needed<br>    // @Observable makes every property access go through<br>    // a tracking layer — SwiftUI records what gets read<br>    // during body execution and watches only those properties<br>  <br>    var body: some View {<br>        Text(vm.name)<br>        Text(&quot;\(vm.followerCount) followers&quot;)<br>    }<br>}</pre><p>SwiftUI automatically tracks which properties are used during rendering and updates only when those specific values change.</p><h4><strong>@Environment — Shared Model Injection</strong></h4><p>@State + plain let works great when a parent directly creates and passes a model to its child. But what about UserSession? Every view in your app might need it — ProfileView, SettingsView, HeaderView views ten levels deep. Passing it through every single parent-child pair would be painful.</p><p>Sharing a model across the view hierarchy with @Environment</p><pre>// At the root of your app:<br>@State private var vm = ProfileViewModel()<br><br>ContentView()<br>    .environment(vm) // inject using .environment(), not .environmentObject()<br><br>// In any child view:<br>struct ChildView: View {<br>    @Environment(ProfileViewModel.self) private var vm<br><br>    var body: some View {<br>        Text(vm.name)<br>    }<br>}</pre><blockquote>⚠️ <strong>Crash risk:</strong> If a view uses @Environment(ProfileViewModel.self) but .environment(vm) was never called higher up, your app crashes at runtime with a clear message. Always inject before using.</blockquote><h3>@Bindable vs. @Binding</h3><p>These two sound almost identical and exist in the same ecosystem, which causes endless confusion. Here is the clearest way to understand them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yquqaihmlHuVrpOPRm9ZHw.png" /></figure><h4>@Binding — the value connector</h4><p>It represents a two-way connection to a value owned by a parent view. It holds no data of its own. when the child writes through it, the parent’s original value updates. When the parent’s value changes, the child re-renders.</p><p>Classic usage: a Bool for sheet dismissal, a String for a reusable TextField, a struct passed down to an edit screen.</p><h4>@Bindable — the object binding enabler</h4><p>It unlocks the $ operator on an @Observable object’s properties. Reading properties works fine without it but the moment a property needs to be passed into a TextField, Toggle, Slider, or any two-way control, @Bindable is what makes $ possible.</p><pre>@Observable final class Settings {<br>    var notificationsEnabled = true<br>    var username = &quot;&quot;<br>}<br><br>struct SettingsView: View {<br>    @Bindable var settings: Settings<br><br>    var body: some View {<br>        Form {<br>            // $ creates a Binding to the property on the @Observable object<br>            TextField(&quot;Username&quot;, text: $settings.username)<br>            Toggle(&quot;Notifications&quot;, isOn: $settings.notificationsEnabled)<br>        }<br>    }<br>}</pre><h4>The tricky edge case: @Bindable inside @Environment</h4><p>Since @Environment doesn&#39;t support $ directly, you need to create a local @Bindable inside the view body when you need to bind to an environment-injected model&#39;s properties:</p><pre>struct ThemeEditorView: View {<br>    @Environment(UserSession.self) private var session<br><br>    var body: some View {<br>        @Bindable var session = session  // local @Bindable from @Environment<br>        TextField(&quot;Display Name&quot;, text: $session.displayName)  // now works<br>    }<br>}</pre><blockquote>🧠 <strong>Memory hook:</strong> @Binding = two-way link to a VALUE in a parent view @Bindable = unlocks $ on an @Observable OBJECT</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dg_0LSztYPktbfFxTAkZMg.jpeg" /></figure><h3>@Observable ≠ Drop-In for @StateObject</h3><p>This is the most important practical warning in this entire post. It’s tempting to assume you can swap ObservableObject + @StateObject for @Observable + @State and move on. For simple models you can. But there&#39;s a subtle and important difference in initialization behavior.</p><p>@StateObject&#39;s initializer accepts an @autoclosure, meaning the model is only ever initialized <strong>once</strong> per view lifecycle even as SwiftUI rebuilds the view struct.</p><p>The @StateObject property wrapper&#39;s initializer signature is:</p><pre>init(wrappedValue thunk: @autoclosure @escaping () -&gt; ObjectType)<br>// The @autoclosure means your initializer expression is LAZILY evaluated<br>// SwiftUI calls it ONCE and caches the result. Even as views rebuild,<br>// the model is only ever initialized once.</pre><p>But @State&#39;s initializer accepts a plain value — no @autoclosure. This means every time SwiftUI rebuilds the view struct (which can happen many times per second), it creates a brand new instance of your model as part of initializing the @State variable, then immediately discards it and restores the stored original.</p><pre>@Observable<br>final class AppSettings {<br>    var theme: Theme = .light<br><br>    init() {<br>        // This runs EVERY TIME SwiftUI rebuilds the parent view<br>        // Multiple AppSettings instances will exist simultaneously<br>        NotificationCenter.default.addObserver(<br>            self,<br>            selector: #selector(handleTermination),<br>            name: UIApplication.willTerminateNotification,<br>            object: nil<br>        )<br>        // Now you have multiple listeners, saving data multiple times<br>    }<br><br>    @objc func handleTermination() {<br>        // This fires from MULTIPLE instances — race condition!<br>        saveToUserDefaults()<br>    }<br>}</pre><blockquote>🚨 <strong>Migration audit checklist:</strong> For every model you’re migrating to <em>@Observable</em>, check if its <em>init()</em> does any of these — if yes, move the logic to a separate <em>setup()</em> method called from <em>.task</em></blockquote><p><strong>Move these OUT of </strong><strong>init():</strong></p><pre>NotificationCenter.default.addObserver(...)<br>// Multiple instances = multiple listeners = race condition<br><br>URLSession.shared.dataTask(...)<br>// Multiple instances = multiple simultaneous requests<br><br>Timer.scheduledTimer(...)<br>// Multiple instances = multiple timers firing simultaneously<br><br>database.open()<br>// Multiple instances = multiple open connections<br><br>FileManager.default.createFile(...)<br>// Multiple instances = file written multiple times</pre><p><strong>Safe to keep in </strong><strong>init():</strong></p><pre>// Plain default values — safe to set multiple times<br>var name: String = &quot;Adam&quot;<br>var count: Int = 0<br>var items: [Item] = []<br>var isLoading: Bool = false</pre><h4>The correct architecture fix</h4><p>The solution is to declare @State models high enough in the hierarchy that their parent view rarely rebuilds — ideally in your App struct, which is never rebuilt during normal operation:</p><pre>@main<br>struct MyApp: App {<br>    // App struct doesn&#39;t get repeatedly rebuilt<br>    // @State here is effectively initialized once for the app&#39;s lifetime<br>    @State private var settings = AppSettings()<br>    @State private var session = UserSession()<br><br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>                .environment(settings)<br>                .environment(session)<br>        }<br>    }<br>}<br><br>@Observable<br>final class AppSettings {<br>    var theme: Theme = .light<br><br>    // Move side effects OUT of init — use .task or .onAppear instead<br>    func setup() {<br>        NotificationCenter.default.addObserver( /* ... */ )<br>    }<br>}<br><br>// In your view:<br>struct RootView: View {<br>    @State private var settings = AppSettings()<br><br>    var body: some View {<br>        ContentView()<br>            .task {<br>                // .task runs ONCE when the view appears<br>                // and cancels when the view disappears<br>                settings.setup()<br>            }<br>    }<br>}</pre><blockquote>💡 Why <strong>.task </strong>and not <strong>.onAppear</strong>? <strong>.task </strong>is tied to the view’s lifetime — it automatically cancels when the view disappears. <strong>.onAppear</strong> has no such cancellation. For async work and one-time setup, <strong>.task</strong> is always the safer choice.</blockquote><h3>@Entry Macro — Clean Environment Values</h3><p>Custom environment values in SwiftUI have always required a lot of boilerplate. The @Entry macro in Xcode 16 collapses all of that into a single line.</p><h4>Before — the old way</h4><pre>struct UserStateKey: EnvironmentKey {<br>    static let defaultValue: UserState = .new<br>}<br><br>extension EnvironmentValues {<br>    var userState: UserState {<br>        get { self[UserStateKey.self] }<br>        set { self[UserStateKey.self] = newValue }<br>    }<br>}</pre><h4>After — with @Entry</h4><pre>extension EnvironmentValues {<br>    @Entry var userState: UserState = .new<br>    @Entry var theme: AppTheme = .default<br>}</pre><h4>When to actually use @Entry?</h4><p>@Entry for an @Observable class adds zero value. It should be used only for <strong>value types</strong> (struct, String, Bool, Int, enum) that you want to pass through the environment.</p><pre>@Observable<br>final class AppTheme {<br>    var isDarkMode: Bool = true<br>    var useLargeText: Bool = false<br>}<br><br>extension EnvironmentValues {<br>    @Entry var preferredFontSize: Double = 16.0<br>}<br><br>// Inject at app level<br>.environment(\.preferredFontSize, theme.useLargeText ? 20.0 : 16.0)<br><br>// Read anywhere deep in the hierarchy<br>struct ProfileView: View {<br>    @Environment(\.preferredFontSize) private var fontSize<br><br>    var body: some View {<br>        Text(&quot;Adam&quot;)<br>            .font(.system(size: fontSize))<br>    }<br>}</pre><blockquote>🎯 <strong>Backward compatible bonus:</strong> Despite being introduced in Xcode 16, @Entry generates backward-compatible Swift code, so you can use it even if your deployment target is below iOS 18. It&#39;s a macro, not an API.</blockquote><h3>Conclusion</h3><p>The shift from ObservableObject to @Observable is not a revolution — it’s a simplification. Combine still has its place for streams and async pipelines. What changed is simply how your models talk to your views. And that conversation just got a lot simpler.</p><p>Less boilerplate.<br>Less confusion.<br>Less guesswork.</p><p>🧭 A simple mental model:<br> → @Observable for state<br> → @Bindable for editing<br> → @Environment for sharing<br> → Combine for streams</p><p>SwiftUI didn’t become more powerful.<br>It became more predictable.</p><p>And that’s what finally makes it feel… right.</p><blockquote>✨ “The best abstractions don’t add complexity — they remove it.”</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec4cec58adbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Part 2] Real-World Example: Building a Cross-Platform App Using Kotlin Multiplatform + Firebase +…]]></title>
            <link>https://medium.com/@purva.r12/part-2-real-world-example-building-a-cross-platform-app-using-kotlin-multiplatform-firebase-e4bce246977e?source=rss-5140c140bdf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4bce246977e</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Purva]]></dc:creator>
            <pubDate>Wed, 17 Dec 2025 09:55:19 GMT</pubDate>
            <atom:updated>2025-12-17T09:55:19.874Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3pvENcDowroi-5k-pmmgEg.png" /></figure><h3>[Part 2] Real-World Example: Building a Cross-Platform App Using Kotlin Multiplatform + Firebase + API (iOS, Android &amp; Desktop)</h3><p>In <strong>Part 1</strong>, we learned how Kotlin Multiplatform (KMP) and Compose Multiplatform (CMP) let us build shared logic that works on iOS, Android, Desktop, and Web.</p><p>Now it’s time to build something practical.</p><p>In this part, we will create a <strong>real, production-ready shared module</strong> that:</p><ul><li>Fetches data from the DummyJSON API</li><li>Stores that data in Firebase Firestore</li><li>Exposes shared ViewModels using KMP</li></ul><p>Is consumed by:</p><ul><li><strong>iOS (SwiftUI app)</strong></li><li><strong>Android (Jetpack Compose app)</strong></li><li><strong>Desktop (Compose Desktop)</strong></li></ul><p>By the end, you’ll have a fully working Architecture where <strong>API → Shared ViewModel → Firebase → UI</strong> works across platforms from one codebase.</p><h3>What we’ll cover first</h3><p>To keep things incremental and easier to reason about, we’ll start with the <strong>foundation</strong>:</p><ul><li>Integrating a remote REST API using <strong>Ktor</strong></li><li>Defining shared data models and repositories</li><li>Exposing data through a <strong>shared ViewModel</strong></li><li>Displaying the data in a shared <strong>Compose UI</strong></li></ul><p>At this stage, the data will flow directly from <strong>API → ViewModel → UI</strong>.</p><h3>What we’ll add next</h3><p>Once the API integration and UI are in place, we’ll extend the same architecture to Persist the data in <strong>Firebase Firestore</strong></p><p>This layered approach reflects how real-world apps are built — starting simple, validating the flow, and then adding persistence and resilience.</p><p>Let’s begin with the API integration.</p><h3>Architecture Overview</h3><pre>DummyJSON API<br>      ↓<br>Ktor HttpClient (commonMain)<br>      ↓<br>Repository (commonMain)<br>      ↓<br>Shared ViewModel (StateFlow)<br>      ↓<br>Compose UI (Android / iOS / Desktop)</pre><p>This structure keeps:</p><ul><li><strong>Networking</strong> in data</li><li><strong>Business logic</strong> in domain</li><li><strong>UI + state</strong> in presentation</li></ul><h3>Step 1: Defining Shared Data Models</h3><p>All models live in commonMain, so they can be reused everywhere.</p><h3>Product Model</h3><pre>@Serializable<br>data class Product(<br>    val id: Int,<br>    val title: String,<br>    val description: String,<br>    val thumbnail: String<br>)</pre><h3>API Response Wrapper</h3><pre>@Serializable<br>data class ProductsResponse(<br>    val products: List&lt;Product&gt;<br>)</pre><p>We use <strong>kotlinx.serialization</strong> so the same models work seamlessly on all platforms.</p><h3>Step 2: Networking with Ktor (Shared API Client)</h3><p>Next, we create a shared API client using <strong>Ktor</strong>.</p><pre>object ApiClient {<br>private val client = HttpClient {<br>       install(ContentNegotiation) {<br>        json(Json { ignoreUnknownKeys = true })<br>     }<br> }<br>suspend fun fetchProducts(): List&lt;Product&gt; {<br>        val response: ProductsResponse =<br>            client.get(&quot;https://dummyjson.com/products?limit=10&quot;).body()<br>        return response.products<br>    }<br>}</pre><h3>Why this works well with KMP</h3><ul><li>Ktor provides platform-specific engines automatically</li><li>JSON parsing is fully shared</li><li>No Android or iOS-specific code leaks into common logic</li></ul><h3>Step 3: Repository Layer</h3><p>The repository abstracts the data source from the rest of the app.</p><pre>class ProductRepository {<br>suspend fun getProducts(): List&lt;Product&gt; {<br>        return ApiClient.fetchProducts()<br>    }<br>}</pre><p>This makes it easy to later:</p><ul><li>Add caching</li><li>Introduce Firebase / local DB</li><li>Swap APIs without touching UI code</li></ul><h3>Step 4: Shared ViewModel using StateFlow</h3><p>Now we expose the data to UI using a <strong>shared ViewModel</strong>.</p><pre>class ProductViewModel {<br>private val repository = ProductRepository()<br>private val _products = MutableStateFlow&lt;List&lt;Product&gt;&gt;(emptyList())<br>    val products: StateFlow&lt;List&lt;Product&gt;&gt; = _products<br>init {<br>     loadProducts()<br> }<br>private fun loadProducts() {<br>        CoroutineScope(Dispatchers.Default).launch {<br>            _products.value = repository.getProducts()<br>        }<br>    }<br>}</pre><h3>Why StateFlow?</h3><ul><li>Works perfectly with Compose</li><li>Easy to observe on all platforms</li><li>Lifecycle-safe when integrated properly</li></ul><h3>Step 5: UI — Product Item with Image Loader</h3><p>We now render products using <strong>Compose Multiplatform UI</strong>.</p><pre>@Composable<br>fun ProductItem(product: Product) {<br>    Card(<br>        modifier = Modifier.fillMaxWidth(),<br>        elevation = CardDefaults.cardElevation(4.dp)<br>    ) {<br>        Row(<br>            modifier = Modifier.padding(12.dp),<br>            verticalAlignment = Alignment.CenterVertically<br>        ) {<br>              Box(<br>                modifier = Modifier<br>                    .size(80.dp)<br>                    .clip(RoundedCornerShape(8.dp))<br>                    .background(MaterialTheme.colorScheme.surfaceVariant),<br>                contentAlignment = Alignment.Center<br>            ) {<br>                KamelImage(<br>                    resource = asyncPainterResource(product.thumbnail),<br>                    contentDescription = product.title,<br>                    modifier = Modifier.fillMaxSize(),<br>                    onLoading = {<br>                        CircularProgressIndicator(<br>                            modifier = Modifier.size(24.dp),<br>                            strokeWidth = 2.dp<br>                        )<br>                    },<br>                    onFailure = {<br>                        Text(&quot;No Image&quot;)<br>                    }<br>                )<br>            }<br>            Spacer(Modifier.width(12.dp))<br>            Column {<br>                Text(product.title, style = MaterialTheme.typography.titleMedium)<br>                Spacer(Modifier.height(4.dp))<br>                Text(product.description, maxLines = 2)<br>            }<br>        }<br>    }<br>}</pre><p>Here we use <strong>Kamel</strong> for image loading, which works across Android, iOS, and Desktop.</p><h3>Step 6: Product Screen</h3><pre>@Composable<br>fun ProductScreen() {<br>    val viewModel = remember { ProductViewModel() }<br>    val products by viewModel.products.collectAsState()<br>    Scaffold(<br>        topBar = {<br>            CenterAlignedTopAppBar(<br>                title = { Text(&quot;Products&quot;) }<br>            )<br>        }<br>    ) { paddingValues -&gt;<br>        LazyColumn(<br>            modifier = Modifier<br>                .fillMaxSize()<br>                .padding(paddingValues)<br>                .padding(horizontal = 16.dp),<br>            verticalArrangement = Arrangement.spacedBy(12.dp)<br>        ) {<br>            items(products) { product -&gt;<br>                ProductItem(product)<br>            }<br>        }<br>    }<br>}</pre><p>This screen is <strong>100% shared UI code</strong>.</p><h3>Step 7: Dependencies &amp; Gradle Setup</h3><p>Key shared dependencies:</p><ul><li><strong>Kotlin Multiplatform</strong></li><li><strong>Compose Multiplatform</strong></li><li><strong>Ktor</strong> for networking</li><li><strong>kotlinx.serialization</strong> for JSON</li><li><strong>Kamel</strong> for image loading</li></ul><p>Platform-specific engines:</p><ul><li>Android &amp; Desktop → OkHttp</li><li>iOS → Darwin</li></ul><p>This ensures stability and performance across all platforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CbyXC_RQUpuDiu96Qnvxdw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-yaQUf8rFA09_bdIx-sXDg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_rYPucB-rmubdTjL2YdxJQ.png" /><figcaption>Desktop, Android and iOS — UI</figcaption></figure><h3>Adding Firebase Firestore Integration</h3><p>Now that our API integration and shared UI are working across platforms, the next step is to <strong>persist data</strong>.</p><p>In real-world apps, data rarely lives only in memory. We usually want to:</p><ul><li>Cache API responses</li><li>Sync remote data to a database</li><li>Serve UI from a reliable source (local / cloud)</li></ul><p>In this section, we’ll integrate <strong>Firebase Firestore</strong> into our existing architecture.</p><h3>Architectural Change</h3><p>We’ll keep the structure clean by:</p><ul><li>Fetching data from the API</li><li>Saving it to Firestore</li><li>Reading data back from Firestore</li><li>Exposing everything via the same shared ViewModel</li></ul><p>This way, <strong>UI never talks directly to Firebase or the API</strong>.</p><h3>Step 1: Firestore Data Source (Shared Interface)</h3><p>We start by creating a Firestore-specific data source inside commonMain.</p><pre>class ProductFirestoreDataSource {<br><br>    private val firestore = Firebase.firestore<br>    private val productsCollection = firestore.collection(&quot;products&quot;)<br><br>    suspend fun saveProducts(products: List&lt;Product&gt;) {<br>        products.forEach { product -&gt;<br>            productsCollection<br>                .document(product.id.toString())<br>                .set(product)<br>        }<br>    }<br><br>    suspend fun getProducts(): List&lt;Product&gt; {<br>        return productsCollection<br>            .get()<br>            .documents<br>            .mapNotNull { it.data&lt;Product&gt;() }<br>    }<br>}</pre><h4>Why this approach works well</h4><ul><li>Uses GitLive Firebase, which supports Android, iOS, and Desktop</li><li>No expect/actual needed</li><li>Firestore logic is isolated from the rest of the app</li><li>Easy to replace or extend later (pagination, offline sync, etc.)</li></ul><h3>Updating the Repository Layer</h3><p>Next, we update the repository to <strong>coordinate API and Firestore</strong>.</p><pre>class ProductRepository {<br><br>    private val firestoreDataSource = ProductFirestoreDataSource()<br><br>    suspend fun fetchFromApiAndStore(): List&lt;Product&gt; {<br>        val products = ApiClient.fetchProducts()<br>        firestoreDataSource.saveProducts(products)<br>        return products<br>    }<br><br>    suspend fun getFromFirestore(): List&lt;Product&gt; {<br>        return firestoreDataSource.getProducts()<br>    }<br>}</pre><p>At this point, the repository is responsible for:</p><ul><li>Fetching fresh data from the API</li><li>Persisting it in Firestore</li><li>Providing a clean API to the ViewModel</li></ul><h3>Shared ViewModel: Firestore-Driven UI</h3><p>Finally, we update the ViewModel so that the UI <strong>always reads from Firestore</strong>.</p><pre>class ProductViewModel {<br><br>    private val repository = ProductRepository()<br><br>    private val _products = MutableStateFlow&lt;List&lt;Product&gt;&gt;(emptyList())<br>    val products: StateFlow&lt;List&lt;Product&gt;&gt; = _products<br><br>    init {<br>        loadProducts()<br>    }<br><br>    private fun loadProducts() {<br>        CoroutineScope(Dispatchers.Default).launch {<br><br>            // Fetch from API and store in Firestore<br>            repository.fetchFromApiAndStore()<br><br>            // Read from Firestore<br>            _products.value = repository.getFromFirestore()<br>        }<br>    }<br>}</pre><h4>Why this is a strong pattern</h4><ul><li>UI does not know about API or Firebase</li><li>Firestore becomes the authoritative data source</li><li>ViewModel logic is shared across platforms</li><li>Compose UI remains untouched</li></ul><blockquote><strong>Note:</strong> Don’t forget to add required Firebase dependencies and configuration.</blockquote><h3>Full Source Code 📦</h3><p>To make this article truly practical and easy to follow, the <strong>entire working codebase</strong> is available in a public repository.</p><p>The repository includes:</p><p>✅ Shared commonMain module (API, Repository, ViewModel)<br>✅ Compose Multiplatform UI (Android, iOS, Desktop)<br>✅ Firebase Firestore integration using GitLive Firebase [for iOS and android]<br>✅ Proper Gradle &amp; KMP setup<br>✅ Platform-specific configurations for Android, iOS &amp; Desktop</p><p>🔗 <strong>GitHub Repository:</strong><br><a href="https://github.com/purva-nayak/Firestore-KMP.git">https://github.com/purva-nayak/Firestore-KMP.git</a></p><p>Feel free to:</p><ul><li>Clone the repo</li><li>Run it on any platform</li><li>Use it as a starter template for your own KMP projects</li></ul><h3>And that’s a wrap 🎬</h3><p>From a single API call to a fully shared <strong>API → ViewModel → Firebase → UI</strong> pipeline running on <strong>iOS, Android, and Desktop</strong> — all from <strong>one Kotlin codebase</strong>.</p><p>👉 No copy-pasting logic.<br>👉 No platform silos.<br>👉 No “rewrite it again for another platform”.</p><p>Just <strong>Kotlin Multiplatform done the right way</strong>.</p><p>If you’ve ever wondered <em>“Can KMP really handle real apps?”</em> — now you have your answer.</p><p>Clone it.<br>Break it.<br>Extend it.<br>Ship it. 🚢</p><p>If this helped you, consider:</p><p>⭐ Starring the repository<br>💬 Sharing feedback or questions<br>✍️ Following along for more KMP deep dives</p><p>Happy building! 👩‍💻👨‍💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4bce246977e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Part 1] Kotlin Multiplatform + Compose Multiplatform: Write Once, Run on iOS, Android & Desktop]]></title>
            <link>https://medium.com/@purva.r12/part-1-kotlin-multiplatform-compose-multiplatform-write-once-run-on-ios-android-desktop-b50a698d17b9?source=rss-5140c140bdf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b50a698d17b9</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[cross-platform]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <dc:creator><![CDATA[Purva]]></dc:creator>
            <pubDate>Wed, 17 Dec 2025 08:30:08 GMT</pubDate>
            <atom:updated>2025-12-17T09:56:26.920Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7j5PA5KJBoG7YsP8v2cjzw.png" /></figure><p>If you’ve been building mobile apps for years, you’ve likely felt the pain:<br>duplicated codebases, duplicated bugs, repeated UI and repeated business logic.</p><p>Now imagine writing all of this <strong>ONCE</strong> and running it on:</p><ul><li>iOS</li><li>Android</li><li>Desktop (Windows/macOS/Linux)</li></ul><p>and still getting native performance.</p><p>Welcome to <strong>Kotlin Multiplatform (KMP)</strong> + <strong>Compose Multiplatform (CMP)<br></strong>A modern approach to shipping consistent apps across platforms. KMP allows you to write <strong>shared business logic once</strong> in Kotlin and use it across iOS, Android, and even backend systems. The best part? You don’t need to rewrite your entire app, your app remains fully native.</p><p>In this post, I’ll walk you through why iOS developers should care about KMP, how to integrate it into your projects, and practical tips from my experience working with shared modules. By the end, you’ll understand how to reduce duplicated code, maintain consistency across platforms, and accelerate development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TQn0udxXpdCSBCBcxTPEQ.png" /><figcaption><a href="https://kotlinlang.org/docs/multiplatform/kmp-overview.html">reference image from kotlin documentation</a></figcaption></figure><h3>Why iOS Developers Should Care</h3><p>As iOS developers, we love Swift and SwiftUI and with good reason. But in a team with Android developers, we often find ourselves rewriting the same logic in Kotlin just to keep Android in sync. That’s where KMP shines: it lets <strong>iOS developers leverage Kotlin without switching ecosystems</strong>.</p><p>With KMP, you can:</p><ul><li><strong>Share network layer logic</strong> (API calls, parsing, error handling)</li><li><strong>Share business rules</strong> (calculations, validations, algorithms)</li><li><strong>Write tests once</strong> for shared code and run them across platforms</li></ul><blockquote><strong><em>Pro Tip:</em></strong><em> Don’t worry about learning Kotlin fully. Basic Kotlin syntax and tooling knowledge are enough. You only share the parts that make sense mainly core logic.</em></blockquote><h3>How to Create a KMP + CMP App</h3><p>There are 2 ways:</p><h4>1. JetBrains KMP Project Wizard</h4><p><a href="https://kmp.jetbrains.com/">https://kmp.jetbrains.com/</a></p><p>Select (any of below / all of the below based on your requirement):</p><ul><li>Android</li><li>iOS</li><li>Desktop</li><li>Web</li><li>Server</li></ul><p>Click <strong>Download</strong>, open in Android Studio, and run on any platform. You instantly get:</p><ul><li>A full working multiplatform project</li><li>Shared UI in commonMain</li><li>Platform folders for iOS/Android/Web/Desktop</li><li>Build configs ready</li><li>Sample screens</li></ul><h4>2. Create Manually from Android Studio</h4><pre>File → New → Kotlin Multiplatform → Select platform from list → finish</pre><p>This generates:</p><blockquote>commonMain/ ← Shared UI + Logic <br>androidMain/ <br>iosMain/ <br>jvmMain/ <br>jsMain/</blockquote><p>You write shared UI + logic in commonMain, and each platform uses it natively.</p><h3>Shared UI Examples</h3><p>Before going into complex networking, let’s start with simple shared UI components that work everywhere.</p><p>These examples live in <strong>commonMain </strong>→<strong> kotlin </strong>→<strong> app.kt </strong>and run on:<br>iOS, Android and Desktop</p><p>Example 1:</p><pre>@Composable<br>fun NameInput() {<br>    var name by remember { mutableStateOf(&quot;&quot;) }<br>    Column(modifier = Modifier.padding(20.dp)) {<br>        Text(&quot;Enter your name:&quot;)<br>        TextField(value = name, onValueChange = { name = it })<br>        Spacer(Modifier.height(12.dp))<br>        Text(&quot;Hello, $name&quot;)<br>    }<br>}</pre><p>Example 2:</p><pre>@Composable<br>fun CounterExample() {<br>    var count by remember { mutableStateOf(0) }<br><br>    Column(<br>        modifier = Modifier.fillMaxSize().padding(20.dp),<br>        horizontalAlignment = Alignment.CenterHorizontally,<br>        verticalArrangement = Arrangement.Center<br>    ) {<br>        Text(&quot;Count: $count&quot;)<br>        Spacer(Modifier.height(16.dp))<br>        Button(onClick = { count++ }) {<br>            Text(&quot;Increase&quot;)<br>        }<br>    }<br>}</pre><h3>Practical Use Case: Sharing the Network Layer</h3><p>One of the most common use cases for KMP is networking. Instead of rewriting API calls, you can write it once using <strong>Ktor</strong>:</p><pre>class ApiService {<br>    private val client = HttpClient()<br>    <br>    suspend fun fetchProducts(): List&lt;Product&gt; {<br>        val response: List&lt;Product&gt; = client.get(&quot;https://api.example.com/products&quot;)<br>        return response<br>    }<br>}</pre><p>This example shows <strong>the minimal KMP shared API call</strong> and <strong>how iOS uses it in Swift </strong>and does not implement networking.<strong> </strong>It simply calls the <strong>shared Kotlin API</strong> using Swift async/await.</p><pre>Task {<br>    do {<br>        let products = try await ApiService().fetchProducts()<br>        print(products)<br>    } catch {<br>        print(&quot;Failed to fetch products: \(error)&quot;)<br>    }<br>}</pre><p>For android,</p><pre>LaunchedEffect(Unit) {<br>    try {<br>        val products = ApiService().fetchProducts()<br>        println(products)<br>    } catch (e: Exception) {<br>        println(&quot;Failed: $e&quot;)<br>    }<br>}</pre><p>For Desktop,</p><pre>fun main() = runBlocking {<br>    try {<br>        val products = ApiService().fetchProducts()<br>        println(products)<br>    } catch (e: Exception) {<br>        println(&quot;Failed to fetch products: $e&quot;)<br>    }<br>}</pre><p>All platforms call the same KMP function:</p><pre>ApiService().fetchProducts()</pre><p>You get:<br>- One API implementation<br>- Shared models<br>- Consistent error handling<br>- Faster development</p><blockquote><strong><em>Pro Tip:</em></strong><em> Start with small modules like networking or business logic. Avoid moving complex UI or platform-specific features to KMP.</em></blockquote><h3>Tips &amp; Lessons from Real Experience</h3><ul><li>Start small share only core logic first.</li><li>Keep platform-specific code clean (UI, gestures, storage).</li><li>Write unit tests in the shared module.</li><li>Coroutines and Swift async/await work together nicely, but you still need to make sure they run on the right thread.</li><li>Don’t over-engineer share what truly makes sense.</li></ul><h3>When to Use KMP (and When Not To)</h3><p><strong>Use KMP for:</strong></p><ul><li>Business logic</li><li>Networking</li><li>Validation</li><li>Shared ViewModels</li><li>Reducing duplication</li></ul><p><strong>Avoid KMP for:</strong></p><ul><li>Complex UI</li><li>Camera/AR/HealthKit/CoreML</li><li>Highly platform-specific features</li><li>Performance-critical native modules</li></ul><h3>Conclusion</h3><p>Kotlin Multiplatform is a game-changer for iOS developers who want <strong>shared code without compromising native quality</strong>. Even integrating <strong>just a few core modules</strong> can save hours of duplicated work, simplify testing, and make your team more productive.</p><p>Start small, write unit tests, and focus on sharing logic not UI. The ecosystem is growing fast, tooling is improving, and the payoff for teams building both iOS and Android apps can be huge.</p><h3>What’s Next?</h3><p><a href="https://medium.com/@purva.r12/part-2-real-world-example-building-a-cross-platform-app-using-kotlin-multiplatform-firebase-e4bce246977e?postPublishedType=initial"><strong>Part 2: Real-World Example — API integration with KMP + Firebase + SwiftUI/Android/Desktop</strong></a></p><p>In Part 2, we’ll build a <strong>real working app</strong> that:</p><ul><li>Fetches products using KMP</li><li>Stores data in Firebase</li><li>Uses shared ViewModels</li><li>Runs on iOS, Android &amp; Desktop</li><li>Shows how each platform consumes the shared code</li></ul><p><strong>Part 1 was the foundation. Part 2 is where everything becomes practical.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b50a698d17b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Combine Framework]]></title>
            <link>https://medium.com/simform-engineering/introduction-to-combine-framework-db0278ec2eb0?source=rss-5140c140bdf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/db0278ec2eb0</guid>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Purva]]></dc:creator>
            <pubDate>Wed, 20 Dec 2023 08:20:44 GMT</pubDate>
            <atom:updated>2023-12-20T08:22:12.482Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Understanding the basics of the Combine framework</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1L98wued315OlUk7naFNPg.png" /></figure><p>Combine is tightly integrated with SwiftUI, Apple’s declarative UI framework. It allows for seamless integration of asynchronous data flow with UI updates, making it easier to build reactive and responsive user interfaces.</p><h3>What is Combine?</h3><ul><li>Combine is a framework introduced by Apple for iOS 13 and macOS 10.15 and later versions. It is designed to handle asynchronous and event-driven programming using a declarative Swift syntax.</li><li>Combine provides a reactive and functional approach to working with asynchronous data streams, making it easier to manage complex asynchronous code and handle events in a more straightforward and intuitive manner.</li></ul><h4>Why should we use Combine?</h4><p>There are several compelling reasons to use Combine in your Swift-based applications:</p><ol><li>Combine enables you to adopt a reactive programming approach, where you define the behavior of your application based on data streams and events. This leads to more declarative code.</li><li>Combine simplifies handling asynchronous tasks like network requests, timers, and notifications.</li><li>Combine’s operators allow you to chain together various data transformations and manipulations in a concise and expressive manner. This promotes code reusability and helps to build complex data structures with minimal boilerplate code.</li><li>Combine provides built-in error-handling mechanisms that propagate errors through the data stream. This makes it easier to handle errors gracefully and take appropriate actions when something goes wrong during asynchronous operations.</li><li>If you are building apps with SwiftUI, Combine is an integral part of the SwiftUI framework. You can seamlessly bind Combine Publishers to SwiftUI views, enabling reactive UI updates based on changes in data.</li><li>Combine helps manage memory efficiently by automatically canceling subscriptions when their associated objects are deallocated. This helps prevent strong reference cycles and potential memory leaks.</li></ol><p>By adopting Combine, you can enhance your Swift-based applications with a more reactive, efficient, and maintainable architecture. Whether you’re working with UI updates, networking, or asynchronous tasks, Combine provides a powerful toolkit to simplify your development process and improve the overall user experience.</p><h4><strong>Challenges developers had to face before the launch of Combine</strong></h4><p>Before the introduction of the Combine framework, developers had to rely on various approaches and third-party libraries to manage asynchronous and event-driven programming in Swift applications.</p><ul><li>Some of the common drawbacks and challenges were callback actions, lack of standardization, error handling complexity, memory management, dependency on third parties, concurrency control, lack of integration with SwiftUI, and many more.</li></ul><h4>The core concept of the Combine framework</h4><p>It revolves around three main components: Publishers, Subscribers and Operators.</p><h4>Publishers</h4><ul><li>A Publisher is a type that produces a sequence of values over time. It represents an asynchronous data source or event stream.</li><li>Publishers can produce values of any data type, including built-in Swift types or custom types. They can also signal errors and a completion signal when the data stream terminates.</li><li>If you’ve developed on Apple platforms before, you can think of a publisher as kind of like NotificationCenter. In fact, NotificationCenter now has a method named publisher(for:object:) that provides a Publisher type that can publish broadcasted notifications.</li><li>Let&#39;s see an example of a publisher:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48cc5a6c282c939d6cd34c6c89df2bdf/href">https://medium.com/media/48cc5a6c282c939d6cd34c6c89df2bdf/href</a></iframe><h4><strong>Subscribers</strong></h4><ul><li>A Subscriber is a type that receives and handles values published by a Publisher.</li><li>Subscribers are an essential component of the Publisher-Subscriber model, which forms the core of the Combine framework.</li><li>Subscribers subscribe to a Publisher to start receiving updates and perform specific actions based on the received data.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2cea5ddba8e5bcb241246eea5fbc35e/href">https://medium.com/media/e2cea5ddba8e5bcb241246eea5fbc35e/href</a></iframe><p>In this example, we have a Just Publisher that produces a single value, which is an array of integers [1, 2, 3, 4, 5]. We then create a Sink Subscriber, which is a built-in Subscriber that receives the produced values and handles them. The Subscriber&#39;s receiveValue closure prints the received array.</p><p>When we subscribe the Subscriber to the Publisher using publisher.subscribe(subscriber), the Subscriber starts receiving updates from the Publisher and prints the received array.</p><p>So the output of this program is:</p><pre>Received array: [1, 2, 3, 4, 5]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xAmz3HfRdOkD1lHxyNp71w.png" /><figcaption>Publisher — Subscriber Pattern (WWDC)</figcaption></figure><h4>Operators</h4><ul><li>Operators are an integral part of the Combine framework.</li><li>Combine provides a wide range of Operators that allow you to transform, filter, and combine values published by Publishers.</li><li>Operators can be used to chain multiple operations together, creating a data pipeline that processes data in a specific way.</li><li>Some commonly used Combine Operators include:</li></ul><ol><li><strong>map</strong>: Transforms each value published by a Publisher into a new value.</li><li><strong>filter</strong>: Selectively reproduces values from a Publisher based on a condition.</li><li><strong>merge</strong>: Combines multiple Publishers into one, merging values from all of them as they arrive.</li><li><strong>combineLatest</strong>: Combines the latest values from multiple Publishers into tuples.</li><li><strong>flatMap</strong>: Transforms each value emitted by a Publisher into a new Publisher and merges the values from all the resulting Publishers.</li></ol><p>To manipulate the data stream, let’s create an example using Combine with a custom Publisher, Subscriber, and some Operators.</p><p>In this example, we’ll use a custom Publisher to emit a sequence of integers, then we’ll use the map operator to transform each value emitted by the Publisher, and finally, a custom Subscriber will receive and print the transformed values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16317daeb65e6c031441bbfde8f05567/href">https://medium.com/media/16317daeb65e6c031441bbfde8f05567/href</a></iframe><p>In this example, we define a custom CustomIntPublisher that conforms to the Publisher protocol. It produces a sequence of integers from 1 to 5. We also define a CustomIntSubscriber that conforms to the Subscriber protocol. This subscriber transforms each received integer by doubling its value and prints the transformed value.</p><p>When we subscribe the CustomIntSubscriber to the CustomIntPublisher, it starts receiving updates from the publisher. The subscriber transforms and prints each received integer, and the transformed values are printed.</p><p>And now the output is:</p><pre>Received transformed value: 2<br>Received transformed value: 4<br>Received transformed value: 6<br>Received transformed value: 8<br>Received transformed value: 10</pre><p>This example demonstrates how to use a custom Publisher, Subscriber, and the map operator in Combine. The map operator allows us to apply a transformation to each value emitted by the Publisher, creating a data processing pipeline with minimal boilerplate code.</p><h3>Conclusion</h3><p>The Combine framework provides a modern and consistent approach to handling asynchronous and reactive programming in Swift applications. It is a valuable tool for developers who want to build responsive, scalable, and efficient applications across various Apple platforms. With Combine’s capabilities, developers can leverage the power of reactive programming to handle complex data flows, asynchronous events, and state management, resulting in more robust and maintainable codebases.</p><blockquote><strong>For more updates on the latest tools and technologies, follow the </strong><a href="https://medium.com/simform-engineering"><strong>Simform Engineering</strong></a><strong> blog.</strong></blockquote><blockquote><strong>Follow Us: </strong><a href="https://twitter.com/simform"><strong>Twitter</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/simform/"><strong>LinkedIn</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db0278ec2eb0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/simform-engineering/introduction-to-combine-framework-db0278ec2eb0">Introduction to Combine Framework</a> was originally published in <a href="https://medium.com/simform-engineering">Simform Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI — Property Wrappers]]></title>
            <link>https://medium.com/simform-engineering/swiftui-property-wrappers-7ea8a5e8874a?source=rss-5140c140bdf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ea8a5e8874a</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[property-wrapper]]></category>
            <category><![CDATA[binding-property-wrapper]]></category>
            <dc:creator><![CDATA[Purva]]></dc:creator>
            <pubDate>Wed, 09 Aug 2023 06:13:12 GMT</pubDate>
            <atom:updated>2023-08-09T08:15:27.596Z</atom:updated>
            <content:encoded><![CDATA[<h3>SwiftUI — Property Wrappers</h3><h4>Understanding property wrappers in the simplest way.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p4ZsiTr9xW-4XfbKGRLpQA.png" /></figure><p>A Property Wrapper is a feature that enables you to add custom behavior to properties. It allows you to define a reusable logic for property access and modification, making your code cleaner and more maintainable.</p><blockquote>The main goal of introducing property wrappers is wrapping properties with logic which can be extracted into the separated struct or class to reuse it across the codebase.</blockquote><blockquote>We know that all our views are structs, which means they can’t be changed but since property wrappers are managed by SwiftUI, whenever the property wrapper value changes, the view invalidates its appearance and reloads the body.</blockquote><h3>Usage</h3><p>A property wrapper can be used with structs, classes, and enums. The init() of the property wrapper is inherently private, so if we want to make use of it, we must explicitly add init() to the property wrapper struct, ensuring that the wrapped value is mandatory and defined within the struct.</p><p>Let’s discuss the types of property wrappers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jy2QH9e7wU1FON48VLxIBA.png" /><figcaption>Types of property wrappers</figcaption></figure><h3>@State</h3><ul><li><strong>@State </strong>property wrapper allows us to modify values inside a struct, which would normally not be allowed because structs are value types.</li><li>When we use <strong>@State</strong> before a property in SwiftUI, we move its storage to a special place managed by SwiftUI. This allows SwiftUI to recreate our structure whenever necessary without losing the data it was holding.</li><li>If we don’t declare <strong>@State</strong> property, it means we can not change the value of that property.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/009f1d08357f82cbc77a58f8fdb09fee/href">https://medium.com/media/009f1d08357f82cbc77a58f8fdb09fee/href</a></iframe><p><strong>count</strong> is a dynamic value. By attaching <strong>@State </strong>to the variable <strong>count</strong>, the drawing system will update the view whenever the value of the <strong>count</strong> is changed.</p><ul><li>You should only access a state property from inside the view’s body or from methods called by it. For this reason, declare your state properties private to prevent clients of your view from accessing them.</li><li>When you change the value of the state property wrapper, the control will reload, and the good practice is whenever you declare a state property wrapper make sure you assign some default value to that property.</li></ul><p><strong><em>Now, should we use state property for all UIControls?</em></strong></p><ul><li>Yes. In the majority of cases in SwiftUI, you will be using state property for your control. This helps you to update the state of your UI control. You don’t need any delegate or data source methods, and with a few lines of code, we can make those reactive changes immediately.</li></ul><h3>@Binding</h3><p>One of the things which SwiftUI promotes is building reusable components in your app. There can be multiple reusable components in one view. When you want the child view’s changes in the parent view, you can use a binding property wrapper. By using this in the child view, you can read or modify the parent view’s source of truth.</p><ul><li><strong>@Binding</strong> does not accept any default value.</li><li><strong>@Binding </strong>has to be public, not private.</li><li>You have to use <strong>$</strong> to pass a binding reference because, without <strong>$,</strong> Swift will pass a copy of the value instead of passing a bindable reference.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5254aba8ef1fb27d11821d175c11ce40/href">https://medium.com/media/5254aba8ef1fb27d11821d175c11ce40/href</a></iframe><h3>@Published</h3><ul><li><strong>@Published</strong> is the most useful property wrapper in SwiftUI. It allows to create the observable objects that automatically announce when changes occur.</li><li>SwiftUI automatically observes changes and re-invokes the body property of views that rely on the data. Whenever an object property marked <strong>@Published</strong> is changed, all views using that object will be reloaded to reflect those changes.</li></ul><p>For example,</p><pre>class Company: ObservableObject {<br>    var employee = [String]()<br>}</pre><p>Here, the property isn’t marked with @Published. No change announcements will ever be sent. You can add data to the array freely, but no views will update.</p><ul><li>Now If you want any change announcements to be sent whenever something is added or removed from the array of <strong>employee</strong>, you have to mark it with @Published, like this:</li></ul><pre>class Company: ObservableObject {<br>    @Published var employee = [String]()<br>}</pre><ul><li>You don’t need to do anything else; the @Published property wrapper effectively adds a <strong>willSet</strong> property observer to the <strong>employee</strong>, so any changes are automatically sent out to observers.</li><li>As you can see, @Published is <em>opt-in. You</em> need to list which properties should cause announcements because the default is that changes don’t cause reloads. This means you can have properties that store caches, properties for internal use, and more. And they won’t force SwiftUI to reload views when they change unless you specifically mark them with @Published.</li></ul><h3>@StateObject</h3><p><strong>@StateObject</strong> is similar to <strong>@State</strong> property, except it’s applied to <strong>ObservableObjects</strong>. An <strong>ObservableObject</strong> protocol is always a reference type (class) and informs SwiftUI whenever one of its <strong>@Published</strong> properties will change.</p><ul><li>When you need to create a reference type inside one of your views and ensure it stays alive for use in that view and others you share it with, that&#39;s where <strong>@StateObject</strong> is used.</li><li>A property marked as <strong>@StateObject</strong> will keep its initially assigned instance as long as the view is needed, even when the struct gets recreated by SwiftUI.</li><li>This is the same behavior you see in @State, except it&#39;s applied to an <strong>ObservableObject </strong>rather than a value type like a struct.</li></ul><p><strong><em>ObservableObject</em></strong><em> is a class protocol because it is inherited from anyObject.</em></p><p>Let&#39;s look at the example below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6218d076d1ff8a1f80b3feb3ac775ad9/href">https://medium.com/media/6218d076d1ff8a1f80b3feb3ac775ad9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*13-dzZHghdsVt4ixHdfqIw.gif" /><figcaption>Use of @StateObject property wrapper</figcaption></figure><h3>@ObservedObject</h3><p>An <strong>@ObservedObject</strong> is used to wrap <strong>ObservableObject</strong> instances that are not created or owned by the view that’s used. It’s applied to the same types of objects as <strong>@StateObject</strong>, and it provides similar features, except a view doesn’t create its own <strong>@ObservedObject</strong> instances.</p><p>There are three key things we need to work with:</p><ul><li>Any type marked with <strong>@ObservedObject</strong> must conform to the <strong>ObservableObject</strong> protocol.</li><li>Observed objects are specifically designed for data that is external to your view, which means it might be shared across more than one view. The <strong>@ObservedObject</strong> property wrapper will automatically make sure the property is watched closely so that important changes will reload any views using it. This also means the data must be created elsewhere, and then sent into your view.</li><li>Not all properties in an observed object cause views to refresh –The <strong>@Published</strong> property wrapper is added to any properties inside an observed object that should cause views to update when they change.</li></ul><p>Now let’s change the property type <strong>@StateObject</strong> to <strong>@ObservedObject</strong> in the previous example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04164b3e5f43d456540c04f6006530f3/href">https://medium.com/media/04164b3e5f43d456540c04f6006530f3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*PAXG-hYwMAsM7_uXkv37FA.gif" /><figcaption>Use of @ObservedObject property wrapper</figcaption></figure><h3>Conclusion</h3><p><strong>ObservedObjects</strong> are usually used when the data is stored outside of the view, so when the view is redrawn, you won’t lose the data. <strong>StateObjects </strong>are usually used when that data needs to be stored inside the view.</p><h3><strong>@EnvironmentObject</strong></h3><p>SwiftUI’s <strong>@EnvironmentObject</strong> property wrappers allow us to create views that rely on shared data, often across an entire SwiftUI app.</p><ul><li><strong>@EnvironmentObject</strong> is created with and stored at the application level. It’s shared data that every view can read/write if they want to.</li><li>Since all views point to the same model, if one view changes the model, all views immediately update, i.e., there’s no risk of getting different parts of your app out of sync.</li></ul><p>Let’s see the example below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a6cfd71fccb6565c83776b96c379cdf/href">https://medium.com/media/2a6cfd71fccb6565c83776b96c379cdf/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48fc8156297c9947c5c263d4b0cd9f44/href">https://medium.com/media/48fc8156297c9947c5c263d4b0cd9f44/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*w-HIR0Nl4kwkzqoRe1lJAw.gif" /><figcaption>Use of @EnvironmentObject property wrapper</figcaption></figure><ul><li><strong>@EnvironmentObject</strong> has a lot in common with <strong>@ObservedObject -</strong> both must refer to a class that conforms to <strong>ObservableObject</strong>, both can be shared across many views, and both will update any views that are watching when significant changes happen. However, <strong>@EnvironmentObject</strong> specifically means “this object will be provided from some outside entity, rather than being created by the current view or specifically passed in.”</li><li>Just like <strong>@ObservedObject</strong>, you never assign a value to an <strong>@EnvironmentObject</strong> property. Instead, it should be passed in from elsewhere, and ultimately you’re probably going to want to use <strong>@StateObject</strong> to create it somewhere.</li><li>However, <em>unlike</em> <strong>@ObservedObject,</strong> we don’t pass our objects into other views by hand. Instead, we send the data into a modifier called <strong>environmentObject()</strong>, which makes the object available in SwiftUI’s environment for that view plus any others inside it.</li><li>If you need to add multiple objects to the environment, you should add multiple <strong>environmentObject()</strong> modifiers; just call them one after the other.</li></ul><h3>@Environment</h3><p><strong>@Environment</strong> property observer is used when we might need to read a device setting or device environment to adjust our view or behavior to match user needs. Examples of these values are current device locale, device current calendar, color scheme (dark or light), and size class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U5m6aECCNVBSEWPG6kXH2g.png" /><figcaption>Use of @Environment property wrapper</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a249d4a20cd11da5ef10bb9bd1bfb11/href">https://medium.com/media/8a249d4a20cd11da5ef10bb9bd1bfb11/href</a></iframe><p>Besides using the predefined values provided by SwiftUI, we can also create our own custom @Environment values using the following three steps:</p><ol><li>Declaring a new environment key type:</li></ol><pre>private struct AnalyticsCategoryEnvironmentKey: EnvironmentKey {<br>    static let defaultValue: String = &quot;none&quot;<br>}</pre><p>2. Defining our environment value property by extending EnvironmentValues:</p><pre>extension EnvironmentValues {<br>    var analyticsCategory: String {<br>        get { self[AnalyticsCategoryEnvironmentKey.self] }<br>        set { self[AnalyticsCategoryEnvironmentKey.self] = newValue }<br>    }<br>}</pre><p>3. Now, we can use the environment value in our views.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/188e16feb1576e98d7b02e29cb4be0e7/href">https://medium.com/media/188e16feb1576e98d7b02e29cb4be0e7/href</a></iframe><p><em>Instead of a </em><strong><em>String</em></strong><em>, we can, of course, use any other type for the environment value.</em></p><h4>Conclusion</h4><p>Today we learned about managing mutable data values and objects in a SwiftUI app with the @State, @Binding, @Environment, @StateObject, @ObservedObject and @EnvironmentObject property wrappers. This includes:</p><ul><li>Use @State and @Binding to manage changes to user interface values.</li><li>Access @Environment values as @Environment view properties or by using the environment view modifier.</li><li>Use @StateObject and @ObservedObject to manage changes to data model objects. The object type must conform to ObservableObject and should <em>publish</em> at least one value.</li><li>For more flexible access to an ObservableObject, instantiate it as a @StateObject , then pass it in the environmentObject view modifier. Declare an @EnvironmentObject property in any subviews that need access to it.</li><li>When prototyping your app, you can use @State and @Binding with structures that model your app’s data. When you’ve worked out how data needs to flow through your app, you can refactor your app to accommodate data types that need to conform to ObservableObject.</li></ul><p>Do try using property wrappers in your project, and if you have any questions or suggestions, let us know in the comments.</p><blockquote><strong>For more updates on the latest tools and technologies, follow the </strong><a href="https://medium.com/simform-engineering"><strong>Simform Engineering</strong></a><strong> blog.</strong></blockquote><blockquote><strong>Follow Us: </strong><a href="https://twitter.com/simform"><strong>Twitter</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/simform/"><strong>LinkedIn</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ea8a5e8874a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/simform-engineering/swiftui-property-wrappers-7ea8a5e8874a">SwiftUI — Property Wrappers</a> was originally published in <a href="https://medium.com/simform-engineering">Simform Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Property wrappers in SwiftUI]]></title>
            <link>https://medium.com/@purva.r12/property-wrappers-in-swiftui-3a0e69ab63d2?source=rss-5140c140bdf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a0e69ab63d2</guid>
            <dc:creator><![CDATA[Purva]]></dc:creator>
            <pubDate>Wed, 14 Sep 2022 06:32:21 GMT</pubDate>
            <atom:updated>2022-09-14T06:32:21.584Z</atom:updated>
            <content:encoded><![CDATA[<p>SwiftUI is a modern way to declare user interfaces for any Apple platform. Create beautiful, dynamic apps faster than ever before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0xVexS6ZYNuVOnrz" /><figcaption>Photo by <a href="https://unsplash.com/@orrbarone?utm_source=medium&amp;utm_medium=referral">James Orr</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>What is property wrapper ?</strong></p><blockquote>A property wrapper is a generic structure that encapsulates read and write access to the property and adds additional behavior to it.</blockquote><p><strong>Why do we need property wrappers?</strong></p><blockquote>We use property wrappers if we need to constrain the available property values, change read/write access (like using DB or other storage), or add some additional methods like value validation.</blockquote><p>Property wrappers were introduced during the WWDC 2019. Property wrappers come with Xcode 11 in swift 5.</p><p>Although property wrappers are a general Swift feature since they were introduced in Swift 5.1, they are particularly common in SwiftUI</p><p>By way of the SwiftUI announcement, we realized that this @ prefix will be used more often, and will be in the future of the Swift language.</p><p>However, these prefixes started to be used not only with SwiftUI but also outside of it. Example: @propertyWrapper</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*7JSJ89DuOyHPR1_Oii7llQ.jpeg" /></figure><h3>Old approach</h3><p>Imagine you are developing an application, and you have an object that contains user profile data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d06a3dd74880f077d4c11772b87f8f12/href">https://medium.com/media/d06a3dd74880f077d4c11772b87f8f12/href</a></iframe><p>You want to add email verification — if the user email address is not valid, the email property must be nil. This would be a good case to use a property wrapper to encapsulate this logic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4483b9edfd9688e08e204f095d3ff5ec/href">https://medium.com/media/4483b9edfd9688e08e204f095d3ff5ec/href</a></iframe><p>We can use this wrapper in the Account structure:</p><pre><strong>struct</strong> <strong>Account</strong> {<br>    <strong>var</strong> firstName: <strong>String</strong><br>    <strong>var</strong> lastName: <strong>String</strong><br>    <strong>var</strong> email: <strong>Email</strong>&lt;<strong>String</strong>&gt;<br>}</pre><p>Now, we are sure that the email property can only contain a valid email address. Everything looks good, except the syntax.</p><pre><strong>let</strong> account = <strong>Account</strong>(firstName: &quot;Test&quot;,<br>                      lastName: &quot;Test&quot;,<br>                      email: <strong>Email</strong>(initialValue: &quot;test@test.com&quot;))</pre><pre>print(account.email.value) <em>// test@test.com</em></pre><p>With a property wrapper, the syntax for initializing, reading, and writing such properties becomes more complex. So, is it possible to avoid this complication and use property wrappers without syntax changes? With <strong><em>Swift 5.1</em></strong>, the answer is <strong><em>yes</em></strong>.</p><h3><strong>New approach: @propertyWrapper Annotation</strong></h3><p><a href="https://swift.org/blog/swift-5-1-released/">Swift 5.1</a> provides a more elegant solution to creating property wrappers, where marking a property wrapper with a <strong>@propertyWrapper</strong> annotation is allowed. Such wrappers have more compact syntax compared to the traditional ones, resulting in more compact and understandable code.</p><p>It can be implemented using both a <strong>struct</strong> or a <strong>class</strong>.</p><p><strong>The </strong><strong>@propertyWrapper annotation has only one requirement: Your wrapper object must contain a non-static property called a </strong><strong>wrappedValue.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7c28c5b038cdf56eb3886c71f7083a4/href">https://medium.com/media/a7c28c5b038cdf56eb3886c71f7083a4/href</a></iframe><p>To define such wrapped property in the code, we need to use the new syntax in our example,</p><pre><strong>struct</strong> <strong>Account</strong> {<br>    <strong>var</strong> firstName: <strong>String</strong><br>    <strong>var</strong> lastName: <strong>String</strong><br>    @<strong>Email var</strong> email: <strong>String?</strong><br>}</pre><p>So, we marked the property with the annotation @. The property type must match the `wrappedValue` type of wrapper. Now, you can work with this property as with the ordinary one.</p><pre>account.email = &quot;valid@test.com&quot;<br>print(account.email) <em>// valid@test.com</em><br>account.email = &quot;invalid&quot;<br>print(account.email) <em>// nil</em></pre><p>looks better now than with the old approach isn’t it?</p><p>But our wrapper implementation has one disadvantage: <strong>It doesn’t allow an initial value for the wrapped value.</strong></p><pre><strong>struct</strong> <strong>Account</strong> {<br>    <strong>var</strong> firstName: <strong>String</strong><br>    <strong>var</strong> lastName: <strong>String</strong><br>    @<strong>Email var</strong> email: <strong>String?</strong> = &quot;valid@test.com&quot; <em>//compilation error.</em><br>}</pre><p>To resolve this, we need to add the following initializer to the wrapper:</p><pre><strong>init</strong>(wrappedValue value: <strong>Value?</strong>) {<br>    <strong>self</strong>.value = value<br>}</pre><p>And that’s it.</p><pre>@<strong>Email var</strong> email: <strong>String?</strong> = &quot;valid@test.com&quot;<br>print(email) <em>// valid@test.com</em><br><br>@<strong>Email var</strong> email: <strong>String?</strong> = &quot;invalid&quot;<br>print(email) <em>// nil</em></pre><h3><strong>The final code of the wrapper is below:</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0991bcc8c04df352c17aa71f7b5572b6/href">https://medium.com/media/0991bcc8c04df352c17aa71f7b5572b6/href</a></iframe><p>Apart from this, there are many property wrappers available in swift all with the purpose to simplify our code. For example,<strong> @State, @StateObject, @Published, @ObservedObject, @EnvironmentObject, @Environment, @Binding, @GestureState, @FetchRequest</strong></p><p>Let me just briefly summarize the basics:</p><ul><li><strong>@State</strong> allows us to modify the values inside the struct which is normally not be allowed because structs are value types.</li><li>Some property wrappers specifically require you to have done extra work elsewhere, and may crash your app if that work isn’t done. For example, <strong>@FetchRequest</strong> expects you to have placed a Core Data managed object context into the environment ahead of time.</li><li>You may apply only one property wrapper at a time, which means <strong>@ObservedObject @Binding var value = SomeClass()</strong> is not allowed.</li><li>Even though some property wrappers look similar (looking at you, <strong>@Environment</strong> and <strong>@EnvironmentObject</strong>!) they are all different and it’s important you use them appropriately.</li></ul><p>That covers the basics, I hope this article helped you to understand the mechanism to use <strong>Property Wrappers</strong> and hope you have learned something new from this article.</p><p><strong>Happy coding!! 🎉</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a0e69ab63d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>