<?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 Taha Bebek on Medium]]></title>
        <description><![CDATA[Stories by Taha Bebek on Medium]]></description>
        <link>https://medium.com/@tahabebek?source=rss-249a73a3316f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ng15-9tMW1jvG8e8c4_JXg.jpeg</url>
            <title>Stories by Taha Bebek on Medium</title>
            <link>https://medium.com/@tahabebek?source=rss-249a73a3316f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 14:20:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tahabebek/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[From Singletons to Actors]]></title>
            <link>https://medium.com/@tahabebek/from-singletons-to-actors-9c7bf12639be?source=rss-249a73a3316f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c7bf12639be</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Taha Bebek]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 19:04:20 GMT</pubDate>
            <atom:updated>2025-03-26T19:04:20.844Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Singleton Anti-Pattern in a Concurrent World ⚠️</h3><p>Swift’s evolution has reached a critical juncture with version 6. The new concurrency model fundamentally challenges one of the most widely-used design patterns in iOS development: the Singleton.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y8Vd2LkdDEK9pWFWvqu_zQ.jpeg" /></figure><p>For years, developers have reached for Singletons to solve shared resource problems — analytics trackers, network managers, persistent stores. But singletons reveal their dangerous nature: unsynchronized access to mutable state across multiple threads creates a perfect storm for data races, inconsistent behavior, and mysterious crashes.</p><p>Swift 6’s compiler now actively warns against these dangers through the Sendable protocol—a contract that guarantees thread safety for types crossing concurrency boundaries. Traditional Singletons with their mutable properties fail these checks by design. Fortunately, Swift provides a powerful alternative: the <strong>actor</strong> model.</p><h3>The Actor Paradigm: Thread Safety by Design</h3><h3>1. Distributed State with Domain Actors</h3><p>Instead of centralizing state in monolithic Singletons, consider distributing it across domain-specific actors:</p><pre>// Before: One massive NetworkManager singleton<br>class NetworkManager {<br>    static let shared = NetworkManager()<br>    var authToken: String?<br>    var activeDownloads: [UUID: URLSessionTask] = [:]<br>    var cachePolicy: URLCache.StoragePolicy = .allowed<br>    // ...dozens more properties and methods<br>}</pre><pre>// After: Domain-specific actors<br>actor AuthenticationService {<br>    private var currentToken: String?<br>    <br>    func authenticate(username: String, password: String) async throws -&gt; String {<br>        let token = try await performAuth(username, password)<br>        currentToken = token<br>        return token<br>    }<br>    <br>    func getCurrentToken() -&gt; String? {<br>        currentToken<br>    }<br>}<br><br>actor DownloadCoordinator {<br>    private var activeDownloads: [UUID: DownloadTask] = [:]<br>    <br>    func startDownload(url: URL) async -&gt; UUID {<br>        let id = UUID()<br>        let task = DownloadTask(url: url)<br>        activeDownloads[id] = task<br>        await task.begin()<br>        return id<br>    }<br>}</pre><p>This approach not only improves thread safety but enhances modularity and testability.</p><h3>2. Contextual Isolation with Task-Local Actors</h3><p>For state that’s relevant only within specific workflows, consider task-local actors that live within the scope of operations:</p><pre>func processUserPhotos() async throws {<br>    let photoProcessor = PhotoProcessingActor()<br>    <br>    for photoID in userPhotoIDs {<br>        let original = try await photoService.fetchPhoto(id: photoID)<br>        let processed = await photoProcessor.apply(filters: userFilters, to: original)<br>        try await photoService.save(processed, id: photoID)<br>    }<br>    <br>    // photoProcessor naturally goes out of scope when done<br>}</pre><pre>actor PhotoProcessingActor {<br>    private var processingCache: [Filter: [UIImage: UIImage]] = [:]<br>    <br>    func apply(filters: [Filter], to image: UIImage) -&gt; UIImage {<br>        // Implementation with caching for the duration of this task<br>    }<br>}</pre><p>This pattern keeps specialized state isolated within its relevant context, avoiding global pollution.</p><h3>3. System Coordination with MainActor</h3><p>For UI updates, @MainActor provides safety without sacrificing simplicity:</p><pre>@MainActor<br>class ApplicationCoordinator {<br>    static let shared = ApplicationCoordinator()<br>    private(set) var currentScreen: AppScreen = .home<br>    private var screenHistory: [AppScreen] = []<br>    <br>    func navigate(to screen: AppScreen) {<br>        screenHistory.append(currentScreen)<br>        currentScreen = screen<br>        updateNavigationUI(for: screen)<br>    }<br>    <br>    func goBack() {<br>        guard let previousScreen = screenHistory.popLast() else { return }<br>        currentScreen = previousScreen<br>        updateNavigationUI(for: previousScreen)<br>    }<br>    <br>    private func updateNavigationUI(for screen: AppScreen) {<br>        // UI updates guaranteed to run on main thread<br>    }<br>}</pre><p>Notice this still uses a “shared” instance — proving that the problem isn’t sharing, but rather unprotected concurrent access to mutable state.</p><h3>Real-World Transformation Strategies</h3><h3>Refactoring Analytics Tracking</h3><p>Analytics tracking is a perfect candidate for actor transformation:</p><pre>// Before: Classic analytics singleton with race condition risks<br>class AnalyticsManager {<br>    static let shared = AnalyticsManager()<br>    private var pendingEvents: [AnalyticsEvent] = []<br>    private var isUploading = false<br>    <br>    func track(_ event: AnalyticsEvent) {<br>        pendingEvents.append(event) // Potential race condition<br>        attemptUpload()<br>    }<br>    <br>    private func attemptUpload() {<br>        if isUploading { return }<br>        isUploading = true // Another race condition!<br>        <br>        // Upload logic<br>    }<br>}</pre><pre>// After: Thread-safe analytics actor<br>actor AnalyticsEngine {<br>    static let shared = AnalyticsEngine()<br>    private var pendingEvents: [AnalyticsEvent] = []<br>    private var isUploading = false<br>    <br>    func track(_ event: AnalyticsEvent) {<br>        pendingEvents.append(event) // Automatically thread-safe!<br>        Task {<br>            await attemptUpload()<br>        }<br>    }<br>    <br>    private func attemptUpload() {<br>        if isUploading { return }<br>        isUploading = true<br>        <br>        // Upload logic<br>    }<br>}</pre><p>Usage becomes:</p><pre>// Track a purchase<br>await AnalyticsEngine.shared.track(.purchase(productID: &quot;pro_subscription&quot;))</pre><h3>Transforming Cache Management</h3><p>Caching is another area where actors shine:</p><pre>actor ImageCache {<br>    private var cache: [URL: CachedImage] = [:]<br>    private let fileManager = FileManager.default<br>    private let diskCacheURL: URL<br>    <br>    init() {<br>        diskCacheURL = fileManager.temporaryDirectory.appendingPathComponent(&quot;ImageCache&quot;)<br>        try? fileManager.createDirectory(at: diskCacheURL, withIntermediateDirectories: true)<br>    }<br>    <br>    func cacheImage(_ image: UIImage, for url: URL) async {<br>        let cachedImage = CachedImage(image: image, timestamp: Date())<br>        cache[url] = cachedImage<br>        <br>        Task.detached(priority: .background) {<br>            await self.saveToDisk(image, for: url)<br>        }<br>    }<br>    <br>    func image(for url: URL) async -&gt; UIImage? {<br>        // Check memory cache<br>        if let cached = cache[url] {<br>            return cached.image<br>        }<br>        <br>        // Check disk cache<br>        return await loadFromDisk(for: url)<br>    }<br>    <br>    private func saveToDisk(_ image: UIImage, for url: URL) async {<br>        // Disk saving implementation<br>    }<br>    <br>    private func loadFromDisk(for url: URL) async -&gt; UIImage? {<br>        // Disk loading implementation<br>    }<br>}</pre><h3>Overcoming Migration Challenges</h3><h3>Handling Synchronous Contexts</h3><p>One challenge when migrating to actors is dealing with synchronous code that can’t use await. For these cases, consider isolation patterns:</p><pre>// Actor for thread-safe state management<br>actor UserSessionState {<br>    static let shared = UserSessionState()<br>    private(set) var isLoggedIn = false<br>    private(set) var currentUserID: String?<br>    <br>    func login(userID: String) {<br>        isLoggedIn = true<br>        currentUserID = userID<br>    }<br>    <br>    func logout() {<br>        isLoggedIn = false<br>        currentUserID = nil<br>    }<br>}</pre><pre>// Synchronous accessor for legacy code<br>extension UserSessionState {<br>    static var currentUserIDIsolated: String? {<br>        // WARNING: This blocks the current thread - use sparingly and only where necessary<br>        let continuation = Task { await shared.currentUserID }.value<br>        return continuation<br>    }<br>}</pre><h3>Progressive Migration Strategy</h3><p>Rather than rewriting everything at once, consider this approach:</p><ol><li><strong>Identify critical race conditions</strong> in existing Singletons</li><li><strong>Create actor shadows</strong> that mirror your Singletons</li><li><strong>Gradually redirect traffic</strong> from Singletons to actors</li><li><strong>Add deprecation warnings</strong> to Singleton methods</li><li><strong>Complete the migration</strong> once all call sites are updated</li></ol><h3>Beyond Singletons: The Actor Ecosystem</h3><p>The actor paradigm isn’t just a replacement for Singletons — it’s an entirely new way of thinking about state isolation:</p><ul><li><strong>Actor hierarchies</strong> for propagating state changes</li><li><strong>Distributed actor systems</strong> for multi-device coordination</li><li><strong>Actor supervision</strong> for error handling and recovery</li><li><strong>Message-passing patterns</strong> for decoupled communication</li></ul><p>By embracing actors now, you’re not just fixing Singleton problems — you’re positioning your codebase for the next generation of Swift development where concurrency is a first-class citizen.</p><p>Thank you for reading until the end. Before you go:</p><p>Check the ultimate git client for mac: <a href="https://xferro.ai/">https://xferro.ai</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c7bf12639be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Git: Version Control for Beginners]]></title>
            <link>https://medium.com/@tahabebek/understanding-git-version-control-for-beginners-3d281b5ae83c?source=rss-249a73a3316f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d281b5ae83c</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Taha Bebek]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 15:35:29 GMT</pubDate>
            <atom:updated>2025-03-26T15:35:29.386Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://xferro.ai/">https://xferro.ai</a></p><figure><img alt="A software engineer coding with his laptop." src="https://cdn-images-1.medium.com/max/1024/1*OF-s-D4qTn4B-SqS-Ec-HQ.jpeg" /></figure><h4>Git is a powerful tool that helps you track changes in your files, collaborate with others, and maintain different versions of your project. If you’ve ever worked on a document, made changes, and then wished you could go back to an earlier version, Git solves this problem elegantly.</h4><h3>What is Git?</h3><p>Git is a distributed version control system designed to track changes in computer files. It was created by Linus Torvalds (the creator of Linux) in 2005 and has since become the standard for software development teams worldwide.</p><p>Think of Git as a time machine for your files. It takes snapshots of your entire project whenever you tell it to, allowing you to:</p><ul><li>Save different versions of your work</li><li>Revert to previous versions if needed</li><li>Work on different features simultaneously without interference</li><li>Collaborate with others without overwriting each other’s work</li></ul><h3>Why Use Git?</h3><p>Even if you’re not a programmer, Git offers significant benefits:</p><ol><li><strong>History tracking</strong>: See who changed what, when, and why</li><li><strong>Backup</strong>: Your entire project history is stored safely</li><li><strong>Experimentation</strong>: Try new ideas without fear of losing your working version</li><li><strong>Collaboration</strong>: Work with others without stepping on each other’s toes</li></ol><h3>Git Basics: Key Concepts</h3><h3>Repositories</h3><p>A Git repository (or “repo”) is essentially a project folder that Git is tracking. It contains all your files plus a special .git directory that stores the history and configuration.</p><h3>Commits</h3><p>A commit is a snapshot of your project at a specific point in time. Think of it as saving a version of your work with a message explaining what changed.</p><h3>Branches</h3><p>Branches let you develop features, fix bugs, or experiment with new ideas in isolation from your main project. You can later merge these changes back when they’re ready.</p><h3>Remote Repositories</h3><p>While Git works perfectly on your local computer, you can also push your repository to services like GitHub, GitLab, or Bitbucket. This creates a backup and makes it easier to share your work with others.</p><h3>Getting Started with Git</h3><p>Here’s a simple workflow to start using Git:</p><ol><li><strong>Install Git</strong>: Download and install from <a href="https://git-scm.com/">git-scm.com</a></li></ol><p><strong>2. Create a repository</strong>: Navigate to your project folder and run:</p><pre>git init</pre><p><strong>3. Add files to track</strong>: Tell Git which files to watch:</p><pre>git add filename.txt</pre><p>Or track all files:</p><pre>git add .</pre><p><strong>4. Commit your changes</strong>: Save a snapshot with a message:</p><pre>git commit -m &quot;Add initial files&quot;</pre><p><strong>5. Check status</strong>: See what files have changed:</p><pre>git status</pre><p><strong>6. View history</strong>: See previous commits:</p><pre>git log</pre><h3>Best Practices for Beginners</h3><ul><li>Commit often with clear, descriptive messages</li><li>Create separate branches for new features or experiments</li><li>Don’t commit sensitive information (passwords, API keys)</li><li>Use .gitignore files to exclude temporary files or build artifacts</li></ul><h3>Moving Beyond the Basics</h3><p>As you get comfortable with Git, you might explore:</p><ul><li>Collaborating using pull requests</li><li>Resolving merge conflicts</li><li>Using Git workflows like Gitflow</li><li>Integrating Git with continuous integration tools</li></ul><h3>Git Clients for Mac</h3><p>While Git can be used directly from the command line, many users prefer a graphical interface. If you’re looking for an AI-backed powerful Git client for Mac, check out Xferro at <a href="https://xferro.ai/">https://xferro.ai</a>. It combines the power of Git with modern AI features to enhance your version control workflow.</p><h3>Conclusion</h3><p>Git might seem complex at first, but it’s worth learning even the basics. Start small by tracking personal projects, and gradually introduce more advanced features as you gain comfort. The ability to track changes, collaborate effectively, and maintain a reliable history of your work will transform how you manage projects.</p><p>Remember that Git is more than just a programming tool — it’s a different way of thinking about how you manage your work, enabling you to be more experimental, collaborative, and organized in any project that involves files changing over time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d281b5ae83c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cursor f*ked up developer’s 4 months of works!]]></title>
            <link>https://medium.com/@tahabebek/cursor-f-ked-up-a-developers-4-months-of-works-2d60f612ec5f?source=rss-249a73a3316f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d60f612ec5f</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Taha Bebek]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 06:27:23 GMT</pubDate>
            <atom:updated>2025-03-26T07:09:17.341Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*tkZZ6B6hh0xJU42ddSDlgQ.jpeg" /></figure><p>I came across a Reddit <a href="https://www.reddit.com/r/cursor/comments/1inoryp/cursor_fck_up_my_4_months_of_works/">post</a> yesterday that made my stomach drop. A fellow developer shared:</p><blockquote><em>“Disclamer, I’m a moron who worked on the same project without thinking about the risk that Cursor could break everything. Yesterday, Cursor (even though I only asked it to feed a view on my UI) destroyed months of development.”</em></blockquote><p>Reading this felt like watching a horror movie where you know something bad is coming but you can’t look away. Months of work, gone. And the worst part? They weren’t doing anything particularly risky — just asking Cursor (an AI-powered code editor) to help with a simple UI view.</p><p>Their follow-up question broke my heart a little:</p><blockquote><em>“How do you back up your projects/versions to ensure that the next action on cursor is reversible?”</em></blockquote><h3>We’ve All Been There</h3><p>Maybe you haven’t lost months of work, but I bet most developers reading this have had that moment of panic when something goes wrong and you realize you haven’t committed your changes in… wait, how long has it been?</p><p>I used to think I was pretty disciplined with Git. Then I started paying attention to my actual habits:</p><ul><li>Sometimes I go hours deep into a problem without committing</li><li>I’ve asked GitHub Copilot to “fix this function” without really thinking about what else it might touch</li><li>I’ve experienced that moment of dread when you realize you just did something destructive and your last commit was too long ago</li></ul><p>The truth is, standard Git workflows were designed before AI tools entered the picture. They rely on us remembering to commit at reasonable intervals. But when you’re in the flow state, especially with AI tools rapidly suggesting changes, that manual process breaks down.</p><h3>The AI Wild West</h3><p>What’s troubling about our Reddit friend’s experience is that it’s becoming more common. AI tools like Cursor, Copilot, and ChatGPT-powered coding assistants are incredibly powerful, but they’re also unpredictable in ways traditional tools aren’t.</p><h3>What I Built to Solve This</h3><p>After experiencing a few too many close calls myself, I started building Xferro. The idea came from a simple question: why can’t Git protection be automatic and continuous, like how Google Docs saves every change?</p><p>Here’s how it works:</p><ol><li>When you create a branch in Xferro, it automatically creates a backup branch</li><li>Every time you make a change to your files — whether manually or through an AI tool — Xferro automatically commits those changes to the backup branch</li><li>These changes are immediately pushed to your remote repository</li></ol><p>The key insight was realizing that backup branches should be separate from your working branches. You still maintain a clean, well-structured history on your main development branches, but you have this parallel history capturing every change if you need it.</p><h3>What This Means for Our Reddit Friend</h3><p>If our unfortunate Reddit developer had been using Xferro, their story would have ended very differently:</p><ol><li>They ask Cursor to help with a UI view</li><li>Cursor goes rogue and messes up their project</li><li>They panic briefly, then remember their backup branch</li><li>They pull the latest state before the disaster from their backup branch</li><li>They’re back in business, having lost minutes rather than months</li></ol><p>Nothing special needed beforehand — no manual commits, no remembering to run backups. Just continuous, automatic protection.</p><h3>If You Want to Try Xferro</h3><p>We’ve just launched our website and started collecting email signups for our beta waitlist. The beta version is nearly ready, and everyone on the list will get access when it launches.</p><p>If you’ve ever felt that moment of panic when something goes wrong in your codebase, or if you work with AI coding tools regularly, you might find Xferro helpful. You can join the waitlist at <a href="https://xferro.com/">xferro.</a>ai.</p><p>More than anything, though, I hope the Reddit developer who lost their work finds a way to recover at least some of it. And I hope their story helps others avoid the same fate, whether through Xferro or through other backup strategies.</p><p>Stay safe out there, fellow coders.</p><p><em>- The developer who built Xferro after one too many close calls</em></p><p>https://xferro.ai</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d60f612ec5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The AI Suggestion Vortex]]></title>
            <link>https://medium.com/@tahabebek/the-ai-suggestion-vortex-b90817fedeaa?source=rss-249a73a3316f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b90817fedeaa</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Taha Bebek]]></dc:creator>
            <pubDate>Tue, 25 Mar 2025 15:41:34 GMT</pubDate>
            <atom:updated>2025-03-25T15:41:34.520Z</atom:updated>
            <content:encoded><![CDATA[<h4>When AI Suggestions Lead to Lost Work</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HAG9rlo2RHGgRGKDPVyTww.jpeg" /></figure><p>Let’s paint a familiar scene: It’s 3 PM, you’re on your third coffee, and you’ve just asked ChatGPT for the fifth different way to optimize that pesky database query.</p><p>“Hmm, this looks promising,” you think, as you copy-paste attempt #5 over your previous code.</p><p>Then it hits you.</p><p>Wait. Was version #2 actually better? Or was it #3? The one with the clever join condition and that weird but efficient subquery?</p><p>…</p><p><em>You’ll never know because you’ve overwritten it four times.</em></p><h3>The AI Suggestion Vortex</h3><p>This is the modern developer’s dilemma. We ask AI for code suggestions, then play “musical chairs” with our files until we can’t remember which version actually worked best.</p><p>It’s like having five chefs each replace your meal with their own creation, then trying to remember how that first delicious bite tasted.</p><p>“Just manually commit each version!” says conventional wisdom.</p><p>But, there’s a problem here. When you’re deep in the flow state, remembering to commit every important iteration is a massive cognitive overhead. Even if you do remember, you end up with an absolute mess of a commit history — dozens of “WIP” or “testing AI suggestion” commits that you’ll later need to clean up.</p><p>And cleaning that history? It’s a special kind of torture. You end up spending a lot of time on tedious operations like un-committing, squashing, rebasing, and merging — each one potentially generating conflicts that need manual resolution. All this just to create a reasonable commit history that won’t make your team question your sanity during code review.</p><h3>The Multi-LLM Experience</h3><p>And it’s not just one LLM. The modern developer’s toolkit is bursting with AI assistants:</p><ul><li>You ask Claude about refactoring your authentication logic</li><li>You prompt Gemini to improve your API endpoint structure</li><li>You have Cursor AI generating inline suggestions as you type</li><li>GitHub Copilot whispers sweet code completions in your ear</li><li>You’ve got Devin running a whole engineering workflow on the side</li></ul><p>Each one gives you different approaches. Each approach overwrites your previous work. And somewhere in that digital mess was the perfect solution that’s now lost to the void.</p><h3>The IDE Limitations</h3><p>“But I use local history in my IDE!” you protest.</p><p>We both know how that ends. Local history has its limits — it doesn’t capture a complete snapshot of your codebase, it’s per file bases, confined to your local machine, and it’s often purged after a certain time period. Restart your IDE after a crash, and you might find those brilliant solutions have vanished.</p><p>And let’s be honest about IDE undo/redo functionality — it’s great until you close the file, or perform certain operations that clear the buffer, or you hit that mysterious limit of undo steps. Try reopening a file after your IDE crashed and pressing Ctrl+Z to get back that brilliant solution from 20 minutes ago.</p><h3>Enter Cursor and Similar Tools</h3><p>Tools like Cursor have tried to address this with their AI-integrated environments. They make it easier to generate and insert code, true. But they don’t solve the fundamental issue of preserving every iteration of your experimentation journey.</p><p>When you overwrite code in Cursor with a new AI suggestion, the previous version still disappears from your active file. You’re still caught in the same trap, just with more efficient AI integration.</p><h3>The Stakes Are High</h3><p>This isn’t just about convenience. Every developer knows the frustration of losing that “perfect solution” they had working an hour ago. It’s not just the code you lose — it’s the time spent recreating it, the mental energy wasted, and sometimes even the elegant approach you can’t quite remember anymore.</p><p>We’ve all been there. You had it working perfectly, then tried “just one more optimization,” and now you can’t get back to that golden state.</p><h3>The Xferro Solution</h3><p>Here’s where Xferro comes to the rescue, without disrupting your productive AI experimentation workflow:</p><ol><li><strong>Backup branches</strong>: For every branch you create, Xferro automatically creates a corresponding backup branch</li><li><strong>Automatic commits</strong>: Every time you make a change to your files, Xferro automatically commits those changes to the backup branch</li><li><strong>Remote protection</strong>: These changes are automatically pushed to the remote repository, ensuring they’re safe from local machine issues</li><li><strong>Zero workflow disruption</strong>: No need to remember to commit between experiments</li></ol><p>That means when you realize “wait, version #2 was actually perfect,” you can easily retrieve it from your backup branch — without interrupting your flow or losing your train of thought.</p><h3>The Future Is Experimental</h3><p>In a world where AI gives us infinite code variations, the developer who can fearlessly experiment without losing work has the advantage.</p><p><strong>Ready to stop losing your best AI-generated solutions?</strong></p><p><a href="https://xferro.ai/">Join the Xferro beta waitlist today →</a></p><p><em>Xferro: Your code, always protected.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b90817fedeaa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Say Goodbye to the Worry of Losing Your Work]]></title>
            <link>https://medium.com/@tahabebek/say-goodbye-to-the-worry-of-losing-your-work-8ccb34eaf610?source=rss-249a73a3316f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ccb34eaf610</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Taha Bebek]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 00:15:16 GMT</pubDate>
            <atom:updated>2025-03-22T15:25:48.782Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HLNtG9tsGBA72t7EaPj3wg.jpeg" /></figure><p>Every software developer has experienced that sinking feeling in their stomach. The moment when you realize hours of carefully crafted code has vanished into the digital void. It’s not just frustrating — it’s demoralizing and costly.</p><p>According to a recent developer productivity survey, the average engineer loses approximately 5–7 hours of work each month due to various code mishaps. That’s nearly a full workday gone, with nothing to show for it except stress and missed deadlines.</p><p>Let’s explore the common scenarios where developers lose their precious work and how Xferro eliminates these worries for good.</p><h3>The Many Ways Developers Lose Their Work</h3><h3>1. The Dreaded Git Reset</h3><p>We’ve all been there. You’re trying to clean up your Git history before a pull request, run a quick git reset --hard, and suddenly realize you included changes you wanted to keep. Your stomach drops as you watch your afternoon&#39;s work disappear in an instant.</p><h3>2. Accidental Discards</h3><p>“Do you want to discard all changes?” You click “Yes” on autopilot, only to realize a split second too late that you meant to save those changes. Now your experimental feature that was working perfectly is gone.</p><h3>3. The LLM Experimentation Rabbit Hole</h3><p>Modern development often involves experimenting with multiple suggestions from LLMs like GitHub Copilot or ChatGPT. You try several approaches, overwriting your files multiple times, then realize the first solution was actually the best — but you’ve lost track of what it was exactly.</p><h3>4. The Coffee Catastrophe</h3><p>Your morning coffee spills over your laptop. The hardware might survive, but what about the uncommitted changes you were working on for the past three hours? Physical accidents result in lost work more often than we’d like to admit.</p><h3>5. The “Just One More Change” Syndrome</h3><p>It’s 6:30 PM, and you decide to make “just one more quick change” before committing. Three hours later, you’ve gone down a refactoring rabbit hole, made dozens of changes across multiple files, and your IDE crashes before you commit anything.</p><h3>6. Branch Switching Blunders</h3><p>You’re working on a feature when an urgent bug fix request comes in. You quickly switch branches without committing, only to find your changes either cause conflicts or silently disappear.</p><h3>7. Power Outages and System Crashes</h3><p>The power goes out or your system freezes, requiring a hard reboot. Despite modern IDEs having some recovery capabilities, they’re not foolproof, and recovery files often contain only partial changes.</p><h3>8. The Collaborative Collision</h3><p>You pull the latest changes from the remote repository without stashing your local changes first, causing merge conflicts that mangle your code beyond recognition.</p><h3>How Xferro Eliminates These Worries</h3><p>Xferro takes a straightforward but powerful approach to preserving your work that’s different from traditional Git workflows.</p><h3>Automatic Backup Branches</h3><p>For every branch you create, Xferro automatically creates a corresponding backup branch. Every time you make a change to your files, Xferro automatically commits those changes to the backup branch and pushes them to the remote repository.</p><p>This means that even if you:</p><ul><li>Accidentally run git reset --hard</li><li>Discard changes in your IDE</li><li>Experience a system crash</li><li>Spill coffee on your laptop</li></ul><p>Your work is safely stored in the backup branch on the remote repository, ready to be recovered.</p><h3>Work Without Interruption</h3><p>With Xferro, you don’t need to change your workflow or remember to create manual safety commits. Continue working as you normally would, and Xferro handles the protection of your work in the background by automatically committing and pushing to your backup branch.</p><h3>Easy Recovery</h3><p>When disaster strikes, recovery is simple. Your backup branch contains all the changes you’ve made, committed automatically as you work. You can easily retrieve any lost work by checking out the backup branch or comparing it with your working branch.</p><h3>No More Lost Work</h3><p>Because every change is automatically committed and pushed to a remote backup branch, the concept of “unsaved work” becomes a thing of the past. Your code is continuously protected without requiring any manual intervention. The peace of mind that comes from knowing your work is always protected is invaluable.</p><h3>With Xferro, you can:</h3><ul><li>Focus entirely on solving problems instead of worrying about losing code</li><li>Experiment freely without fear of losing working versions</li><li>Recover from accidents and hardware failures with minimal stress</li><li>Have a complete record of all your changes safely stored in backup branches</li></ul><h3>Join the Xferro Beta</h3><p>We’re excited to announce that Xferro’s website is now live, and we’re collecting emails for our beta launch waitlist. The beta version will be ready very soon, and we’ll email everyone on the list when it’s available.</p><p>Sign up today to be among the first developers to say goodbye to the worry of losing your work forever.</p><p><a href="https://xferro.com/">Join the Xferro Beta Waitlist</a></p><p><em>Xferro: Your code, always protected.</em></p><p>Original Post: <a href="https://www.xferro.ai/post/say-goodbye-to-the-worry-of-losing-your-work">https://www.xferro.ai/post/say-goodbye-to-the-worry-of-losing-your-work</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ccb34eaf610" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scalable and Modular System Design for the simplest iOS App]]></title>
            <link>https://medium.com/@tahabebek/scalable-and-modular-system-design-for-the-simplest-ios-app-7a1a3873992b?source=rss-249a73a3316f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a1a3873992b</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Taha Bebek]]></dc:creator>
            <pubDate>Fri, 15 Dec 2023 22:59:28 GMT</pubDate>
            <atom:updated>2023-12-30T10:45:23.647Z</atom:updated>
            <content:encoded><![CDATA[<p>As an iOS engineer passionate about crafting efficient and maintainable applications, I want to share a case study that illustrates the power of modular architecture in app development, specifically using Swift and SwiftUI.</p><h3>The App Overview</h3><p>Our app is simple, featuring two main screens: the Feed Feature and the Detail View Feature.<br><strong>Feed Feature</strong>: This is the first screen of our app, where users see a list of posts. Each post comprises a picture and a title.</p><p><strong>Detail View Feature:</strong> Upon selecting a post from the Feed Feature, users are navigated to this screen. It displays the post’s detailed information, including a large image, title, and descriptive text.</p><h3>Components</h3><ol><li><strong>FeedFeature</strong>: Manages the display of posts.<br> — Dependencies: ApiClientProtocol, NavigationManagerProtocol, AnalyticsProtocol, Models</li><li><strong>DetailViewFeature</strong>: Shows detailed information about a selected post.<br> — Dependencies: NavigationManagerProtocol, AnalyticsProtocol, Models</li><li><strong>DependencyManager</strong>: Provides necessary dependencies for features.<br> — Dependencies: ApiClientImplementation, NetworkServiceImplementation, AnalyticsImplementation, URLSessionImplementation, Models</li><li><strong>NavigationManager</strong>: Creates features and handles navigation between screens.<br> — Dependencies: DependencyManagerProtocol, FeedFeature, DetailFeature, Models</li><li><strong>ApiClient</strong>: Interfaces with the network to fetch post data.<br> — Dependencies: NetworkServiceProtocol, Models</li><li>N<strong>etworkService</strong>: Executes the network requests.<br> Dependencies: URLSessionProtocol</li><li><strong>AnalyticsManager</strong>: Tracks user interactions and app events for analytics purposes.</li></ol><h3><strong>Interaction Between Components</strong></h3><p><strong>1- Dependency Injection:</strong> DependencyManager plays a crucial role in injecting dependencies into features. For instance, it supplies ApiClient, Analytics, and other necessary components to FeedFeature.</p><p><strong>2- Data Flow:</strong> When a post is selected in FeedFeature, the NavigationManager is invoked to transition to DetailViewFeature, carrying along the necessary data (like post details).</p><p><strong>3- Modularity:</strong> Each component (like FeedFeature, DetailViewFeature) operates independently but communicates with others via well-defined interfaces (like protocols). This setup allows for easy updates and maintenance of individual components.</p><h3>The Power of Modular Architecture in iOS</h3><p><strong>Building Independently Compilable Features</strong><br>The core of a well-structured iOS app lies in its modular architecture. By encapsulating each feature into its own module or framework, we achieve a level of independence that simplifies both development and testing. Tools like Swift Package Manager or Xcode Frameworks are essential here, allowing us to manage these modules effectively.</p><p>Imagine working on a complex app with multiple features — the ability to compile and run each feature independently is a massive time-saver. It also reduces the cognitive load, letting us focus on one aspect of the app at a time.</p><p><strong>Protocols and Substitutability</strong><br>Using protocols like ApiClientProtocol, NavigationManagerProtocol, and others ensures that components are not tightly coupled to specific implementations. This allows for easy substitution, such as using mock implementations for testing or switching out components without affecting the rest of the app.</p><h3>Dependency Graph</h3><p>Here is the dependency graph of this system. Dependencies are lazily created by the dependency manager bottom up and provided to the navigation manager as a scope. Creating the dependencies bottom-up is called dependency inversion. The arrow shows the import direction; for example, DependencyManager depends on URLSession. Every box in this graph is a separate module, located in an Xcode framework or a swift package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p__kOxcvAjqcesugDamgBA.png" /></figure><h3>Leveraging SwiftUI Previews with Mocked Dependencies</h3><p>SwiftUI has been a game-changer, especially with its Preview feature. With a modular architecture, the ability to see real-time changes in the feature you are working on without the need to compile the entire app is nothing short of amazing.</p><p><strong>Crafting Realistic Previews</strong><br>By creating mock implementations of dependencies, we can inject controlled, predictable data into our SwiftUI views. This setup is perfect for developing features in isolation. It allows us to experiment with different UI states without the overhead of dealing with the actual backend or data sources.</p><h3>A Practical Example</h3><p>The FeedFeature requires data from an ApiClient and AnalyticsManager. Instead of relying on the actual implementations, we can use mock versions that provide predefined responses.</p><pre>struct FeedFeaturePreview: PreviewProvider {<br>  static var previews: some View {<br>    FeedFeatureView(apiClient: MockApiClient(), …)<br>   }<br>}</pre><h3>The Benefits Are Clear</h3><p>The advantages of this methodology are numerous:</p><p><strong>Rapid Iteration:</strong> You can tweak and refine UI components on the fly, significantly speeding up the development process.</p><p><strong>Focused Testing:</strong> With mocked data, you can ensure your UI behaves exactly as expected under various conditions, without external dependencies.</p><p><strong>Collaborative and Parallel Development:</strong> Different team members can work on separate features simultaneously without stepping on each other’s toes.</p><p><strong>Modularity: </strong>You can develop, compile, test, and distribute modules independently.</p><h3>Summary</h3><p>Our app is a well-structured example of modular iOS architecture, emphasizing independence, testability, and maintainability. Each component has a specific role and communicates with others through defined interfaces and dependency injection, creating a robust and scalable design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a1a3873992b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Macros]]></title>
            <link>https://medium.com/@tahabebek/swift-macros-36417a8557a?source=rss-249a73a3316f------2</link>
            <guid isPermaLink="false">https://medium.com/p/36417a8557a</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-macros]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Taha Bebek]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 14:34:09 GMT</pubDate>
            <atom:updated>2023-07-20T14:34:09.550Z</atom:updated>
            <content:encoded><![CDATA[<p>Swift Macros allow you to generate repetitive code at compile time, making your app’s codebase easier to read and less tedious to write.</p><h3>There are two types of macros:</h3><ul><li><strong>Freestanding</strong> macros stand in place of something else in your code. They always start with a hashtag (#) sign.</li></ul><pre>#caseDetection // Freestanding Macro</pre><ul><li><strong>Attached</strong> macros are used as attributes on declarations in your code. They start with an @ sign.</li></ul><pre>@CaseDetection // Attached Macro</pre><h3>Create new Macro</h3><p>Macros must be created in a special Package that depends on the <a href="https://github.com/apple/swift-syntax">swift-syntax</a> library.</p><p>To create a new Macro, go to New -&gt; Package and select Swift Macro.</p><p>Type the name of your Macro and create the Package.</p><h3>Macro Package structure</h3><p>Inside the newly created Package, you will find some auto-generated files:</p><ul><li>[Macro name].swift, where you declare the signature of your Macro</li><li>main.swift, where you can test the behavior of the Macro</li><li>[Macro name]Macro.swift, where you write the actual implementation of the Macro</li><li>[Macro name]Tests.swift, where you write the tests of the Macro implementation</li></ul><h3>Macro roles</h3><p>A single Macro can have multiple roles that will define its behavior.</p><p>The available roles are:</p><h3>@freestanding(expression)</h3><p>Creates a piece of code that returns a value.</p><p>Protocol: ExpressionMacro</p><p>Example:</p><p>A macro that produces both a value and a string containing the source code that generated the value.</p><pre>@freestanding(expression)<br>macro #stringify&lt;T&gt;(_ value: T) → (T, String)<br><br>#stringify(x + y)</pre><p>This expands to:</p><pre>(x + y, &quot;x + y&quot;)</pre><h3>@freestanding(declaration)</h3><p>Creates one or more declarations.</p><p>Protocol: DeclarationMacro</p><p>Example:</p><p>A macro that generates data structures from a template or other data format (e.g., JSON).</p><pre>@freestanding (declaration, names: arbitrary)<br>macro jsonModel(String)<br><br>struct JSONValue: Codable {<br>  #jsonModel(&quot;&quot;&quot;<br>  &quot;name&quot;: &quot;Produce&quot;,<br>  &quot;shelves&quot;: [<br>    {<br>      &quot;name&quot;: &quot;Discount Produce&quot;,<br>      &quot;product&quot;: {<br>        &quot;name&quot;: &quot;Banana&quot;,<br>        &quot;points&quot;: 200,<br>        &quot;description&quot;: &quot;A banana that&#39;s perfectly ripe.&quot;<br>      }<br>    }<br>  ]<br>  &quot;&quot;&quot;)<br>}</pre><p>This expands to:</p><pre>struct JSONValue: Codable {<br>  var name: String<br>  var shelves: [Shelves]<br><br>  struct Shelves: Codable {<br>    var name: String<br>    var product: Product<br>    struct Product: Codable {<br>      var description: String<br>      var name: String<br>      var points: Double<br>    }<br>  }<br>}</pre><h3>@attached(peer)</h3><p>Adds new declarations alongside the declaration it’s applied to.</p><p>Protocol: PeerMacro</p><p>Example:</p><p>A macro that creates an async function off of a completion one.</p><pre>@attached(peer, names: overloaded)<br>public macro AddAsync()<br><br>@AddAsync<br>func test(arg1: String, completion: (String?) -&gt; Void) {<br>  <br>}</pre><p>This will expand to:</p><pre>func test(arg1: String, completion: (String?) -&gt; Void) {<br>  <br>}<br><br>func test(arg1: String) async -&gt; String? {<br>  await withCheckedContinuation { continuation in<br>    self.test(arg1: arg1) { object in<br>      continuation.resume(returning: object)<br>    }<br>  }<br>}</pre><h3>@attached(accessor)</h3><p>Accessor macros allow a macro to add accessors to a property, turning a stored property into a computed property.</p><p>Protocol: AccessorMacro</p><p>Example:</p><p>A macro that can be applied to a stored property to instead access a dictionary keyed by the property name.</p><pre>@attached(accessor) <br>macro DictionaryStorage(key: String? = nil)<br><br>struct MyStruct {<br>  var storage: [AnyHashable: Any] = [:]<br>  <br>  @DictionaryStorage<br>  var name: String<br>  <br>  @DictionaryStorage(key: &quot;birth_date&quot;)<br>  var birthDate: Date?<br>}</pre><p>This will expand to:</p><pre>struct MyStruct {<br>  var storage: [String: Any] = [:]<br>  <br>  var name: String {<br>    get { <br>      storage[&quot;name&quot;]! as! String<br>    }<br>    <br>    set {<br>      storage[&quot;name&quot;] = newValue<br>    }<br>  }<br>  <br>  var birthDate: Date? {<br>    get {<br>      storage[&quot;birth_date&quot;] as Date?<br>    }<br>    <br>    set {<br>      if let newValue {<br>        storage[&quot;birth_date&quot;] = newValue<br>      } else {<br>        storage.removeValue(forKey: &quot;birth_date&quot;)<br>      }<br>    }<br>  }<br>}</pre><h3>@attached (memberAttribute)</h3><p>Adds attributes to the declarations in the type/extension it’s applied to.</p><p>Protocol: MemberAttributeMacro</p><p>Example:</p><p>A macro that adds the @objc attribute to every member of the type or extension unless that member either already has an @objc macro or has @nonobjc on it.</p><pre>@attached(memberAttribute)<br>macro MyObjCMembers()<br><br>@MyObjCMembers extension MyClass {<br>  func f() { }<br>  var answer: Int { 42 }<br>  @objc(doG) func g() { }<br>  @nonobjc func h() { }<br>}</pre><p>This will expand to:</p><pre>extension MyClass {<br>  @objc func f() { }<br><br>@objc var answer: Int { 42 }<br>  @objc(doG) func g() { }<br>  @nonobjc func h() { }<br>}</pre><h3>@attached (member)</h3><p>Adds new declarations inside the type/extension it’s applied to.</p><p>Protocol: MemberMacro</p><p>Example:</p><p>A macro that defines static members to ease the definition of an OptionSet.</p><pre>@attached(member, names: named(rawValue), arbitrary) <br>macro OptionSetMembers()<br><br>@OptionSetMembers<br>struct MyOptions: OptionSet {<br>  enum Option: Int {<br>    case a<br>    case b<br>    case c<br>  }<br>}</pre><p>This will expand to:</p><pre>struct MyOptions: OptionSet {<br>  enum Option: Int {<br>    case a<br>    case b<br>    case c<br>  }<br>  <br>  var rawValue: Int = 0<br>  <br>  static var a = MyOptions(rawValue: 1 &lt;&lt; Option.a.rawValue)<br>  static var b = MyOptions(rawValue: 1 &lt;&lt; Option.b.rawValue)<br>  static var c = MyOptions(rawValue: 1 &lt;&lt; Option.c.rawValue)<br>}</pre><h3>@attached(conformance)</h3><p>Adds conformances to protocols.</p><p>Protocol: ConformanceMacro</p><p>Example:</p><p>A macro that makes enums with associated values conform to RawRepresentable.</p><pre>@attached(conformance)<br>public macro StringRawRepresentation()<br><br>@StringRawRepresentation<br>enum Visa {<br>    case tourist<br>    case business<br>    case student<br>    case other(String)<br>}</pre><p>This will expand to:</p><pre>enum Visa: RawRepresentable {<br>    var rawValue: String {<br>        switch self {<br>        case .tourist:<br>            return &quot;tourist&quot;<br>        case .business:<br>            return &quot;business&quot;<br>        case .student:<br>            return &quot;student&quot;<br>        case .other(let value):<br>            return value<br>        }<br>    }<br><br>init?(rawValue: String) {<br>        switch rawValue {<br>        case &quot;tourist&quot;:<br>            self = .tourist<br>        case &quot;business&quot;:<br>            self = .business<br>        case &quot;student&quot;:<br>            self = .student<br>        default:<br>            self = .other(rawValue)<br>        }<br>    }<br>}</pre><h3>Role composition</h3><p>A macro may have multiple attached roles.</p><p>Example:</p><p>A macro that wraps up all the stored properties of the given type in a dictionary, turning them into computed properties.</p><pre>/// This macro composes three different kinds of macro expansion:<br>///   * Member-attribute macro expansion, to put itself on all stored properties<br>///     of the type it is attached to.<br>///   * Member macro expansion, to add a `_storage` property with the actual<br>///     dictionary.<br>///   * Accessor macro expansion, to turn the stored properties into computed<br>///     properties that look for values in the `_storage` property.<br>@attached(accessor)<br>@attached(member, names: named(_storage))<br>@attached(memberAttribute)<br>public macro DictionaryStorage()<br><br>@DictionaryStorage<br>struct Point {<br>  var x: Int = 1<br>  var y: Int = 2<br>}</pre><p>This will expand to:</p><pre>@DictionaryStorage<br>struct Point {<br>  var _storage: [String: Any] = [:]<br>  <br>  @DictionaryStorage<br>   var x: Int = 1<br>   {<br>     get {<br>        _storage[&quot;x&quot;, default: 1] as! Int<br>       }<br>     set {<br>        _storage[&quot;x&quot;] = newValue<br>     }<br>   }<br> <br>   @DictionaryStorage<br>   var y: Int = 2<br>   {<br>      get {<br>         _storage[&quot;y&quot;, default: 2] as! Int<br>       }<br>       set {<br>         _storage[&quot;y&quot;] = newValue<br>      }<br>   }<br>}</pre><h3>Build Macro</h3><p>We will create a Macro that creates an async function from a completion one.</p><p>To start building this Macro, we need to create the Macro <strong>signature</strong>.</p><p>To do this, go to AddSync.swift file and add.</p><pre>@attached(peer, names: overloaded)<br>public macro AddAsync() = #externalMacro(module: &quot;AddAsyncMacros&quot;, type: &quot;AddAsyncMacro&quot;)</pre><p>Then to implement the actual Macro, go to the AddSyncMacro.swift file.</p><pre>public struct AddAsyncMacro: PeerMacro {<br>  <br>   public static func expansion(of node: AttributeSyntax, providingPeersOf declaration: some DeclSyntaxProtocol, in context: some MacroExpansionContext) throws -&gt; [DeclSyntax] {<br>      // Implement macro<br>   }<br>}</pre><p>We have to cast the declaration to the desired syntax.</p><p>In this case, the Macro can only be attached to a function, so that we will cast it to FunctionDeclSyntax.</p><p>So, inside the expansion method, add the following:</p><pre>guard let functionDecl = declaration.as(FunctionDeclSyntax.self) else {<br>   // TODO: Throw error<br>}<br> <br>return []</pre><p>Now, before we continue, we need to write a test that checks whether the implementation of the Macro generates the code we expect.</p><p>So, in AddAsyncTests.swift file, add:</p><pre>func test_AddAsync() {<br>    assertMacroExpansion(<br>        &quot;&quot;&quot;<br>        @AddAsync<br>        func test(arg1: String, completion: (String?) -&gt; Void) {<br>          <br>        }<br>        &quot;&quot;&quot;,<br>        expandedSource: &quot;&quot;&quot;<br>        <br>        func test(arg1: String, completion: (String?) -&gt; Void) {<br>          <br>        }<br>        <br>        func test(arg1: String) async -&gt; String? {<br>          await withCheckedContinuation { continuation in<br>            self.test(arg1: arg1) { object in<br>              continuation.resume(returning: object)<br>            }<br>          }<br>        }<br>        &quot;&quot;&quot;,<br>        macros: testMacros<br>    )<br>}</pre><p>Once that is in place, let’s add a breakpoint at return [] inside the expansion method and run the test.</p><p>Once we hit the breakpoint, run po functionDecl inside the debug console to get this long description:</p><pre>FunctionDeclSyntax<br>├─attributes: AttributeListSyntax<br>│ ╰─[0]: AttributeSyntax<br>│   ├─atSignToken: atSign<br>│   ╰─attributeName: SimpleTypeIdentifierSyntax<br>│     ╰─name: identifier(&quot;AddAsync&quot;)<br>├─funcKeyword: keyword(SwiftSyntax.Keyword.func)<br>├─identifier: identifier(&quot;test&quot;)<br>├─signature: FunctionSignatureSyntax<br>│ ╰─input: ParameterClauseSyntax<br>│   ├─leftParen: leftParen<br>│   ├─parameterList: FunctionParameterListSyntax<br>│   │ ├─[0]: FunctionParameterSyntax<br>│   │ │ ├─firstName: identifier(&quot;arg1&quot;)<br>│   │ │ ├─colon: colon<br>│   │ │ ├─type: SimpleTypeIdentifierSyntax<br>│   │ │ │ ╰─name: identifier(&quot;String&quot;)<br>│   │ │ ╰─trailingComma: comma<br>│   │ ╰─[1]: FunctionParameterSyntax<br>│   │   ├─firstName: identifier(&quot;completion&quot;)<br>│   │   ├─colon: colon<br>│   │   ╰─type: FunctionTypeSyntax<br>│   │     ├─leftParen: leftParen<br>│   │     ├─arguments: TupleTypeElementListSyntax<br>│   │     │ ╰─[0]: TupleTypeElementSyntax<br>│   │     │   ╰─type: OptionalTypeSyntax<br>│   │     │     ├─wrappedType: SimpleTypeIdentifierSyntax<br>│   │     │     │ ╰─name: identifier(&quot;String&quot;)<br>│   │     │     ╰─questionMark: postfixQuestionMark<br>│   │     ├─rightParen: rightParen<br>│   │     ╰─output: ReturnClauseSyntax<br>│   │       ├─arrow: arrow<br>│   │       ╰─returnType: SimpleTypeIdentifierSyntax<br>│   │         ╰─name: identifier(&quot;Void&quot;)<br>│   ╰─rightParen: rightParen<br>╰─body: CodeBlockSyntax<br>  ├─leftBrace: leftBrace<br>  ├─statements: CodeBlockItemListSyntax<br>  ╰─rightBrace: rightBrace</pre><h3>Retrieve the first argument name</h3><pre>let signature = functionDecl.signature.as(FunctionSignatureSyntax.self)<br>let parameters = signature?.input.parameterList<br>let firstParameter = parameters?.first<br>let parameterName = firstParameter.firstName // -&gt; arg1</pre><p>Now, let’s complete the AddAsync implementation.</p><pre>if let signature = functionDecl.signature.as(FunctionSignatureSyntax.self) {<br>   let parameters = signature.input.parameterList<br>      <br>   // 1.<br>   if let completion = parameters.last,<br>      let completionType = completion.type.as(FunctionTypeSyntax.self)?.arguments.first,<br>   let remainPara = FunctionParameterListSyntax(parameters.removingLast()) {<br>        <br>   // 2. returns &quot;arg1: String&quot;<br>   let functionArgs = remainPara.map { parameter -&gt; String in<br>      guard let paraType = parameter.type.as(SimpleTypeIdentifierSyntax.self)?.name else { return &quot;&quot; }<br>      return &quot;\(parameter.firstName): \(paraType)&quot;<br>   }.joined(separator: &quot;, &quot;)<br>        <br>   // 3. returns &quot;arg1: arg1&quot;<br>   let calledArgs = remainPara.map { &quot;\($0.firstName): \($0.firstName)&quot; }.joined(separator: &quot;, &quot;)<br>        <br>   // 4.<br>   return [<br>   &quot;&quot;&quot;<br>   func \(functionDecl.identifier)(\(raw: functionArgs)) async -&gt; \(completionType) {<br>      await withCheckedContinuation { continuation in<br>         self.\(functionDecl.identifier)(\(raw: calledArgs)) { object in<br>            continuation.resume(returning: object)<br>         }<br>      }<br>   }<br>   &quot;&quot;&quot;<br>   ]<br>   }<br>}</pre><h3>Show custom errors</h3><p>Macros allow you to show custom errors to the user.</p><p>For example, in case the user placed the macro on a struct, but that macro can only be used with functions.</p><p>In this case, you can throw an error, and it will be automatically shown in Xcode.</p><pre>enum AsyncError: Error, CustomStringConvertible {<br>  <br>  case onlyFunction<br>  <br>  var description: String {<br>    switch self {<br>    case .onlyFunction:<br>      return &quot;@AddAsync can be attached only to functions.&quot;<br>    }<br>  }<br>}<br><br>// Inside expansion method. <br>guard let functionDecl = declaration.as(FunctionDeclSyntax.self) else {<br>   throw AsyncError.onlyFunction // &lt;- Error thrown here<br>}</pre><h3>Test Macro usage</h3><p>To test the behavior of the AddAsync macro.</p><p>Go to the main.swift file and add:</p><pre>struct AsyncFunctions {<br>  <br>  @AddAsync<br>  func test(arg1: String, completion: (String) -&gt; Void) {<br>    <br>  }<br>}<br> <br>func testing() async {<br>  let result = await AsyncFunctions().test(arg1: &quot;Blob&quot;)<br>}</pre><h3>Show Macro generated code</h3><p>To expand a Macro in code and see the automatically generated code, right-click on the Macro and choose Expand Macro from the menu.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36417a8557a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced SwiftUI Tutorial -Creating a Style-able Address Form Component — Part 1]]></title>
            <link>https://medium.com/@tahabebek/advanced-swiftui-tutorial-creating-a-style-able-address-form-component-part-1-52bbd4f3ccbd?source=rss-249a73a3316f------2</link>
            <guid isPermaLink="false">https://medium.com/p/52bbd4f3ccbd</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Taha Bebek]]></dc:creator>
            <pubDate>Sun, 04 Dec 2022 05:10:30 GMT</pubDate>
            <atom:updated>2022-12-06T23:44:36.262Z</atom:updated>
            <content:encoded><![CDATA[<h3>SwiftUI Tutorial -Creating a Style-able Address Form Component — Part 1</h3><p>Hello everyone, With this post, I am starting a new series where I will create a style-able address form component in SwiftUI. This address form will be extensible, meaning it will be possible to create new styles. It will be possible to set the style globally. It will have validation and autocorrection for each different field type. It will also come with 4 built-in styles,</p><ul><li>default</li><li>rounded</li><li>floating</li><li>capsule</li></ul><p>This is how the entry fields will look like for the 4 different styles in order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*nBz-8zpnc6HU6FH3UfcDOA.png" /></figure><p>Let’s get started. To create our AddressForm, first we need to create an EntryField. So let’s start from there.</p><p># Create a new project, choose SwiftUI and Swift, name it AddressForm.<br># Create a new SwiftUI file, name it EntryField.</p><p>EntryField needs following properties:</p><ul><li>content (input view)</li><li>leadingAccessoryView (home icon on the left side)</li><li>trailingAccessoryView (info icon on the left side)</li><li>string (value entered)</li></ul><pre>struct EntryField&lt;Content: View, LeadingAccessoryView: View, TrailingAccessoryView: View&gt;: View {<br>  @State var value: String<br>  let content: Content<br>  let leadingAccessoryView: LeadingAccessoryView<br>  let trailingAccessoryView: TrailingAccessoryView<br>  <br>  var body: some View {<br>    <br>  }<br>}</pre><p>To be able to see this on preview, we can create an EntryFieldView struct:</p><pre>struct EntryFieldView: View {<br>  @State var value: String = &quot;&quot;<br>   <br>  var body: some View {<br>    EntryField(value: value,<br>               content: TextField(&quot;Street Address&quot;, text: $value),<br>               leadingAccessoryView: Image(systemName: &quot;house&quot;),<br>               trailingAccessoryView: Image(systemName: &quot;info.circle&quot;))<br>  }<br>}</pre><p>Return it from EntryField_Previews:</p><pre>struct EntryField_Previews: PreviewProvider {<br>  static var previews: some View {<br>    EntryFieldView()<br>  }<br>}</pre><p>Fill the body of the EntryField:</p><pre> var body: some View {<br>    VStack {<br>      HStack {<br>        leadingAccessoryView<br>        content<br>        trailingAccessoryView<br>      }<br>      Spacer()<br>    }<br>    .padding()<br>  }<br>}</pre><p>Gray out the accessory views a little bit,</p><pre>var body: some View {<br>    VStack {<br>      HStack {<br>        leadingAccessoryView<br>          .opacity(0.5)<br>        content<br>        trailingAccessoryView<br>          .opacity(0.5)<br>      }<br>      Spacer()<br>    }<br>    .padding()<br>  }<br>}</pre><p>By now, we already have our default style entry field and we can see it in the preview:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*CpMfohq2-aWj7jQ-MhpgVA.png" /></figure><p>Let’s see if our binding is working by adding an onChange modifier to EntryFieldView:</p><pre> var body: some View {<br>    EntryField(...)<br>    .onChange(of: value) { newValue in<br>      print(newValue)<br>    }<br>  }</pre><p>Put EntryFieldView into the body of ContentView, run the app on simulator and see that it is logging the new values while we type in the EntryField.</p><pre>struct ContentView: View {<br>    var body: some View {<br>        VStack {<br>          EntryFieldView()<br>          Spacer()<br>        }<br>        .padding()<br>    }<br>}</pre><p># Making the EntryField style-able</p><p>We have an EntryField, which is good. But we want to make it style-able. We want to type something like:</p><pre>EntryField(...)<br>  .style(.capsule)</pre><p>or</p><pre>EntryField(...)<br>  .style(.floating) </pre><p>, and set the style globally. We also want to make it extensible so that we can add more styles in the future. To achieve this, we need to define an EntryFieldStyle protocol.</p><p>With the help of this protocol, we can create different styles that conform to it. Like:</p><pre>DefaultEntryFieldStyle: EntryFieldStyle<br>RoundedEntryFieldStyle: EntryFieldStyle<br>FloatingEntryFieldStyle: EntryFieldStyle<br>CapsuleEntryFieldStyle: EntryFieldStyle</pre><p>When we create an EntryField, we can pass it an EntryFieldStyle, and EntryFieldStyleConfiguration instance which will hold values needed to create an EntryField. This way EntryField can tell the a specific EntryFieldStyle to create an EntryField with an EntryFieldStyleConfiguration. Let’s do it.</p><p># Create a new struct named EntryFieldStyleConfiguration:</p><pre>public struct EntryFieldStyleConfiguration {<br>  @State var value: String<br>  let content: Content<br>  let leadingAccessoryView: LeadingAccessoryView<br>  let trailingAccessoryView: TrailingAccessoryView<br>  <br>  struct Content: View {<br>    var underlyingView: AnyView<br><br>    var body: some View {<br>      underlyingView<br>    }<br>  }<br>  <br>  struct LeadingAccessoryView: View {<br>    var underlyingView: AnyView<br><br>    var body: some View {<br>      underlyingView<br>    }<br>  }<br>  <br>  struct TrailingAccessoryView: View {<br>    var underlyingView: AnyView<br><br>    var body: some View {<br>      underlyingView<br>    }<br>  }<br>}</pre><p># Create a new protocol named EntryFieldStyle:</p><pre>public protocol EntryFieldStyle {<br>  associatedtype Body: View<br>  func makeBody(_ configuration: EntryFieldStyleConfiguration) -&gt; Body<br>}</pre><p>Now that we have a configuration struct and a style protocol, let’s create our first style, which will be the default style.</p><p># Create a struct named DefaultEntryField which will receive only the configuration as an argument:</p><pre>struct DefaultEntryField: View {<br>  let configuration: EntryFieldStyleConfiguration<br>  <br>  var body: some View {<br>    VStack {<br>      HStack {<br>        configuration.leadingAccessoryView<br>          .opacity(0.5)<br>        configuration.content<br>        configuration.trailingAccessoryView<br>          .opacity(0.5)<br>      }<br>      Spacer()<br>    }<br>    .padding()<br>  }<br>}</pre><p># Create a struct named DefaultEntryFieldStyle which conforms to EntryFieldStyle:</p><pre>struct DefaultEntryFieldStyle: EntryFieldStyle {<br>  func makeBody(_ configuration: EntryFieldStyleConfiguration) -&gt; some View {<br>    DefaultEntryField(configuration: configuration)<br>  }<br>}</pre><p>Now we can pass the style to the initializer of EntryField, which will create the specific style EntryField for us.</p><p>We are ready to use our first style. Add style variable to EntryField , and call style.makeBody like this:</p><pre>struct EntryField&lt;Style: EntryFieldStyle,... {<br>...<br>let style: EntryFieldStyle<br><br>  var body: some View {<br>    AnyView (<br>      style.makeBody(<br>        .init(<br>          value: value,<br>          label: .init(underlyingView: AnyView(label)),<br>          content: .init(underlyingView: AnyView(content)),<br>          leadingAccessoryView: .init(underlyingView: AnyView(leadingAccessoryView)),<br>          trailingAccessoryView:.init(underlyingView: AnyView(trailingAccessoryView))))<br>    )<br>  }<br>}</pre><p>Update EntryFieldView and ContentView to pass the style:</p><pre>EntryField(value: value,<br>           content: TextField(&quot;Street Address&quot;, text: $value),<br>           leadingAccessoryView: Image(systemName: &quot;house&quot;),<br>           trailingAccessoryView: Image(systemName: &quot;info.circle&quot;),<br>           style: DefaultEntryFieldStyle())</pre><p>We have an style-able EntryField now. We can add as many styles as we want. We will add 3 more styles in this tutorial.</p><p>Before that though, there are more urgent needs. We want to use the dot syntax, and we want to be able to set the style globally, like for the whole app.</p><p>To achieve all of this, we need to set entry field style as an environment value. Let’s do that.</p><p># Create a file named EntryFieldEnvironmentValue:</p><pre>import SwiftUI<br><br>struct EntryFieldEnvironmentKey: EnvironmentKey {<br>  static let defaultValue: any EntryFieldStyle = DefaultEntryFieldStyle()<br><br>}<br><br>extension EnvironmentValues {<br>  var entryFieldStyle: any EntryFieldStyle {<br>    get { self[EntryFieldEnvironmentKey.self] }<br>    set { self[EntryFieldEnvironmentKey.self] = newValue }<br>  }<br>}<br><br>public extension View {<br>  func entryFieldStyle(_ style: some EntryFieldStyle) -&gt; some View {<br>    environment(\.entryFieldStyle, style)<br>  }<br>}</pre><p># Now let’s use the environment value for the style variable. In EntryField struct, replace:</p><pre>let style: EntryFieldStyle</pre><p>with:</p><pre>@Environment(\.entryFieldStyle) var style</pre><p>, we don’t need to define the Style generic type anymore so delete its declaration. Final result should be this</p><pre>struct EntryField&lt;Content: View, LeadingAccessoryView: View, TrailingAccessoryView: View&gt;: View {<br>  ...<br>}</pre><p>Since we added the environment value for the entryFieldType, we have a default value now. So if you don’t pass a style, it will be the default:</p><pre>EntryField(value: value,<br>           content: TextField(&quot;Street Address&quot;, text: $value),<br>           leadingAccessoryView: Image(systemName: &quot;house&quot;),<br>           trailingAccessoryView: Image(systemName: &quot;info.circle&quot;))</pre><p>Or you can set it like this:</p><pre> EntryField(value: value,<br>            content: TextField(&quot;Street Address&quot;, text: $value),<br>            leadingAccessoryView: Image(systemName: &quot;house&quot;),<br>            trailingAccessoryView: Image(systemName: &quot;info.circle&quot;))<br>    .entryFieldStyle( DefaultEntryFieldStyle())</pre><p>Last thing before we add other styles is adding the ability to use the dot syntax. We can achieve it by adding a static variable to each style in an extension.</p><p># Create a file named EntryFieldStyleExtensions and add this:</p><pre>extension EntryFieldStyle where Self == DefaultEntryFieldStyle {<br>  static var `default`: DefaultEntryFieldStyle { return .init() }<br>}</pre><p>Finally, we can set it with the dot syntax.</p><pre>EntryField(value: value,<br>           content: TextField(&quot;Street Address&quot;, text: $value),<br>           leadingAccessoryView: Image(systemName: &quot;house&quot;),<br>           trailingAccessoryView: Image(systemName: &quot;info.circle&quot;))<br>  .entryFieldStyle(.default)</pre><p># Now, let’s create RoundedEntryField. We need 3 things:</p><ul><li>RoundedEntryField</li><li>RoundedEntryFieldStyle</li><li>Dot syntax extension</li></ul><p>For RoundedEntryField, we need one more variable, the label above the input area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*-xu_Wg-_6U3e6LTxkclcPQ.png" /></figure><p># Let’s add this to EntryField and EntryFieldStyleConfiguration, and update the call site which is the EntryFieldView instance.</p><p>EntryField:</p><pre>//Add label to EntryField<br>struct EntryField&lt;Label: View /*...*/&gt; {<br>  @State var value: String<br>  let label: Label //Add label here!!!<br>  <br>  /...<br>  var body: some View {<br>    AnyView (<br>      style.makeBody(<br>        .init(<br>          value: value,<br>          label: .init(underlyingView: AnyView(label)), //and here!!!<br>          content: .init(underlyingView: AnyView(content)),<br>          leadingAccessoryView: .init(underlyingView: AnyView(leadingAccessoryView)),<br>          trailingAccessoryView:.init(underlyingView: AnyView(trailingAccessoryView))))<br>    )<br>  }<br>}</pre><p>EntryFieldView:</p><pre>//Update EntryFieldView callsite<br>EntryField(value: value,<br>               label: Text(&quot;Street Address&quot;), //add label here!!!<br>               content: TextField(&quot;Street Address&quot;, text: $value),<br>               leadingAccessoryView: Image(systemName: &quot;house&quot;),<br>               trailingAccessoryView: Image(systemName: &quot;info.circle&quot;))</pre><p>EntryFieldStyleConfiguration:</p><pre>public struct EntryFieldStyleConfiguration {<br>  //...  <br>  let label: Label<br>  <br>  struct Label: View {<br>    var underlyingView: AnyView<br><br>    var body: some View {<br>      underlyingView<br>    }<br>  }<br>  //...<br>}</pre><p># With the addition of label, we can create RoundedEntryField, and RoundedEntryFieldStyle.</p><p>RoundedEntryField:</p><pre>struct RoundedEntryField: View {<br>  let configuration: EntryFieldStyleConfiguration<br>  <br>  var body: some View {<br>    VStack {<br>      VStack (alignment: .leading, spacing: 4) {<br>        configuration.label<br>          .font(.caption)<br>          .foregroundStyle(.secondary)<br>        HStack(alignment: .center, spacing: 8) {<br>          Spacer(minLength: 8)<br>          configuration.leadingAccessoryView<br>            .opacity(0.5)<br>          configuration.content<br>          configuration.trailingAccessoryView<br>            .padding(.horizontal, 16)<br>            .opacity(0.5)<br>        }<br>        .frame(minHeight: 54, alignment: .center)<br>        .background {<br>          Color.gray.opacity(0.2)<br>        }<br>        .cornerRadius(8)<br>      }<br>      Spacer()<br>    }<br>    .padding()<br>  }<br>}</pre><p>RoundedEntryFieldStyle:</p><pre>struct RoundedEntryFieldStyle: EntryFieldStyle {<br>  func makeBody(_ configuration: EntryFieldStyleConfiguration) -&gt; some View {<br>    RoundedEntryField(configuration: configuration)<br>  }<br>}</pre><p>EntryFieldStyleExtentions:</p><pre>extension EntryFieldStyle where Self == RoundedEntryFieldStyle {<br>  static var rounded: RoundedEntryFieldStyle { return .init() }<br>}</pre><p>Now let’s add a preview and see how our RoundedEntryField looks like. Put this into RoundedEntryField file:</p><pre>struct RoundedEntryFieldView: View {<br>  @State var value: String = &quot;&quot;<br>   <br>  var body: some View {<br>    EntryField(value: value,<br>               label: Text(&quot;Street Address&quot;),<br>               content: TextField(&quot;Street Address&quot;, text: $value),<br>               leadingAccessoryView: Image(systemName: &quot;house&quot;),<br>               trailingAccessoryView: Image(systemName: &quot;info.circle&quot;))<br>    .entryFieldStyle(.rounded)<br>    .onChange(of: value) { newValue in<br>      print(newValue)<br>    }<br>  }<br>}<br><br>struct RoundedEntryField_Previews: PreviewProvider {<br>  static var previews: some View {<br>    RoundedEntryFieldView()<br>  }<br>}</pre><p>It looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*reB1sCsCic4lVEzKgzUFqQ.png" /></figure><p>This is it for the first part of this tutorial. We created a style-able EntryField and added 2 styles so far.</p><p>In the upcoming parts, to finish our AddressForm, we will add the following:</p><p><strong># 2 more entry fields styles</strong></p><ul><li>FloatingEntryFieldStyle</li><li>CapsuleEntryFieldStyle</li></ul><p><strong># 5 entry field types</strong></p><ul><li>NameField</li><li>EmailField</li><li>PhoneField</li><li>StreetField</li><li>CityField</li><li>StateField</li><li>ZipCodeField</li></ul><p><strong># Autoformatting inputs</strong></p><p><strong># Validation for each field and for the AddressForm</strong></p><p><strong># Accessibility</strong></p><p><strong># Localization</strong></p><p>Follow me on twitter: https://twitter.com/_tahabebek</p><p>Watch this tutorial on youtube: <a href="https://www.youtube.com/watch?v=CakZ9z1qdgE&amp;t=2496s">https://www.youtube.com/watch?v=CakZ9z1qdgE&amp;t=2496s</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52bbd4f3ccbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Generics in Swift]]></title>
            <link>https://medium.com/better-programming/generics-in-swift-2cd549c53075?source=rss-249a73a3316f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cd549c53075</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Taha Bebek]]></dc:creator>
            <pubDate>Tue, 22 Nov 2022 02:09:17 GMT</pubDate>
            <atom:updated>2022-12-02T09:28:24.103Z</atom:updated>
            <content:encoded><![CDATA[<h4>Know what it is, how to use them, and when</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*E1P8Z-_oCdOjhDEdOJt8WQ.png" /><figcaption>image by author</figcaption></figure><h3>What Are Generics?</h3><p>Generic programming is a technique for writing reusable code while maintaining type safety. It is a kind of polymorphism called “parametric polymorphism.” Polymorphism means using a single interface or name that works with multiple types.</p><p>There are mainly three different types of polymorphism:</p><ul><li>Ad hoc polymorphism. We can define multiple functions with the same name, but different types called ad hoc polymorphism.</li><li>Subtype polymorphism. If a function expects a class C, we can also pass in a subclass of C. This is called subtype polymorphism.</li><li>Parametric polymorphism. If a function has a generic parameter, we can pass it in different types. This is called parametric polymorphism.</li></ul><h3>Why We Need Generics</h3><p>One of the reasons is less code. Instead of writing this:</p><pre>func square(value: Int) -&gt; Int{…}<br>func square(value: Double) -&gt; Double {…}<br>func square(value: Float) -&gt; Float {…}</pre><p>We can write this:</p><pre>func square&lt;T&gt;(value: T) -&gt; T {…}</pre><p>This way, we can write a single function instead of writing multiple functions to handle different parameter types (function overloading). Here T stands for type. You can put anything there; it doesn’t have to be T, and it doesn’t matter what we put. This function could also be defined as:</p><pre>func square&lt;PutAnythingHere&gt;(value: PutAnythingHere) -&gt; PutAnythingHere {…}</pre><p>This means that if you pass an object with type x to this function, it will return an object with type x.</p><h3>Why Not Use Any?</h3><pre>func square(value: Any) -&gt; Any{}</pre><p>This is not good and will not work because we can pass any type and return any type, which doesn’t make sense.</p><p>We use generics to express and limit what kind of types a class works with. For example, when we declare an Array, we declare it like this:</p><pre>var arr: Array&lt;Int&gt;<br>arr = [1,2,3,4,5]</pre><p>This means arr is an array of integers. This way, we can not insert anything other than integers into this array. We can define an array of integers because Array has a generic type defined like this:</p><pre>public struct Array&lt;Element&gt; {…}</pre><p>If you really want to have a heterogeneous array that can hold any item, then you can define it as:</p><pre>var arr: Array&lt;Any&gt;<br>arr = [1, “Two”, 5.8, Car(), Calendar(), OperationQueue()]</pre><p>which is something you should avoid unless you really know what you are doing because it can open a can of worms. The reason is if you want to use the elements in the array, you need to force unwrap them like this:</p><pre>var obj0 = arr[0] as! Int<br>var obj1 = arr[1] as! String<br>var obj2 = arr[2] as! Double<br>var obj3 = arr[3] as! Car<br>var obj4 = arr[4] as! Calendar<br>var obj5 = arr[5] as! OperationQueue</pre><p>You see how problematic and dangerous this is. It feels like your app can crash at any time. Simple code like this can lead to crashes:</p><pre>var obj0 = arr[0] as! String</pre><pre>error: Execution was interrupted, reason: signal SIGABRT.<br>Could not cast value of type ‘Swift.Int’ (0x1b9ac80b8) <br>to ‘Swift.String’ (0x1b9ac6258).</pre><p>So, stick with a Generic type when you create an array.</p><h3>What if We Want To Work With a Specific Subset of Types?</h3><p>Our square function above is problematic because we can pass any type to it. What if we pass a String?</p><pre>func square&lt;T&gt;(value: T) -&gt; T {…}<br>square(“Some string here”)</pre><p>Strings don’t have squares, so this doesn’t make any sense. We need to restrict our generic further to be a numeric type like this:</p><pre>func square&lt;T: Numeric&gt;(value: T) -&gt; T {…}</pre><p>This way, we can only pass values with types that conform to numeric protocol. We know that all numeric values have squares, so our function has the right limitations now, and nobody can pass something that doesn’t make sense. If we try to mess with it by calling it like:</p><pre>square(“Some string here”)</pre><p>the compiler gives this error below and doesn’t allow it to happen:</p><pre>function ‘square(value:)’ requires that ‘String’ conform to ‘Numeric’</pre><p>We restricted the generic type by limiting it to conforming to a protocol. We could also use a class that will restrict the generic type to subclass from a specific class.</p><pre><br>class SomeClass {<br> var name: String = “class name”<br>}<br><br>func printClassName&lt;T: SomeClass&gt;(value: T) {<br> print(value.name)<br>}<br><br>class SomeSubClass: SomeClass {}<br><br>printClassName(value: SomeSubClass())<br>//prints:<br>//class name</pre><h3>Generics in the Bigger Scope</h3><p>Functions and methods aren’t the only generic types. We can also have generic structs, classes, and enums.</p><h4><strong>Example 1</strong></h4><p>Let&#39;s create a stack struct that works with a generic type. We need to define this stack with a type we name Object, so we can only push, pop, and peek the same type.</p><pre><br>struct Stack&lt;Object&gt; {<br> private var objects: [Object] = []<br> <br> mutating func push(object: Object) {<br>   objects.append(object)<br> }<br> <br> mutating func pop() -&gt; Object? {<br>   return objects.popLast()<br> }<br> <br> func peek() -&gt; Object? {<br>   return objects.last<br> }<br>}</pre><p>Here we defined a struct, which should have an object type predefined. For example, a stack of functions will be like this:</p><pre>typealias Work = () -&gt; Void<br>var stack: Stack&lt;Work&gt; = Stack()<br>stack.push {…}</pre><p>Here, we limited our stack to a stack of Work functions. We can only push functions to this stack, specifically functions typealiased as Work which receives no argument and returns nothing. We can call the functions in this stack like this:</p><pre>while let work = stack.pop() {<br> work()<br>}</pre><h4><strong>Example 2</strong></h4><p>Let’s create a SwiftUI View that receives another View as a subview. View in SwiftUI is a protocol, so we need to define a struct that conforms to the View protocol and passes a subview as a generic type that also conforms to the View protocol.</p><pre>struct SomeView&lt;Content: View&gt;: View {<br> let subview: Content<br> var body: some View {<br>   subview<br> }<br>}</pre><p>We can create an instance of SomeView by passing a Text or an Image as a subview, because both Text and Image conform to View protocol, like this:</p><pre>let someView = SomeView(subview: Text(&quot;some text…&quot;))<br>let anotherView = SomeView(subview: Image(&quot;some_image&quot;))</pre><h4><strong>Example 3</strong></h4><p>Here’s the definition of Optional in Swift:</p><pre>enum Optional&lt;Wrapped&gt; { <br> case none <br> case some(Wrapped)<br>}</pre><p>Optional is a generic type. When we choose a value for Wrapped, we get a concrete type. For example, Optional&lt;Int&gt; or Optional&lt;UIView&gt; are both concrete types.</p><p>When we want to turn a generic type into a concrete type, we have to choose exactly one concrete type for each generic parameter.</p><p>Generics are used throughout the Swift standard library. For example:</p><ul><li>Collections like Array, Set, and Dictionary.</li><li>Optional uses a generic parameter to abstract over its wrapped type.</li><li>Result has two generic parameters — one representing a successful value and another representing an error.</li><li>Unsafe[Mutable]Pointer is generic over the type of memory it points to.</li><li>Key paths are generic over both their root type and the resulting value type.</li></ul><h3>Protocols With Associated Types</h3><p>Associated type is a placeholder name for a type used as part of a protocol. The actual type for the associated type isn’t specified until the protocol is adopted. It is a generic type that is declared in a protocol. This is how we can use generics in protocols.</p><p>What if we want to define our Stack protocol instead of a Struct? Let’s try. If we write the line below:</p><pre>protocol Stack&lt;Object&gt;</pre><p>the compiler gives this error and tells us how to use generics with protocols. Here’s the message:</p><pre>An associated type named ‘Object’ must be declared in the protocol ‘Stack’ <br>or a protocol it inherits</pre><p>So, how can we define our Stack as a protocol? Like this:</p><pre>protocol Stack {<br> associatedtype Object<br> <br> mutating func push(object: Object)<br> mutating func pop() -&gt; Object?<br> func peek() -&gt; Object?<br>}</pre><p>The only difference is, instead of defining it as protocol Stack&lt;Object&gt; {…}, we defined it as protocol Stack { associatedtype Object }. Now, let’s create a Stack struct that conforms to the Stack protocol.</p><pre><br>struct WorkStack: Stack {<br>  typealias Object = Work<br>  private var objects: [Work] = []<br> <br>  mutating func push(object: @escaping Work) {<br>   objects.append(object)<br>  }<br>  <br>  mutating func pop() -&gt; Work? {<br>   return objects.popLast()<br>  }<br>   <br>  func peek() -&gt; Work? {<br>   return objects.last<br>  }<br>}</pre><p>In WorkStack, we can delete the typealias line because the compiler can infer the associated type from function declarations and understand that the associated type is Work. So, we can define it like this:</p><pre>struct WorkStack: Stack {<br> private var objects: [Work] = []<br> <br> mutating func push(object: @escaping Work) {<br>   objects.append(object)<br> }<br> <br> mutating func pop() -&gt; Work? {<br>   return objects.popLast()<br> }<br> <br> func peek() -&gt; Work? {<br>   return objects.last<br> }<br>}<br><br>//We can create an instance of WorkStack and use it like this:<br>var workStack = WorkStack()<br>workStack.push {…}<br>while let work = workStack.pop() {<br> work()<br>}</pre><p>We can create other stacks that conform to the Stack protocol like IntStack, StringStack, CarStack, etc., like how we did above. But what if we want to create a generic stack that conforms to Stack protocol which can be a stack of any specific type? This is how we can achieve it:</p><pre>struct MyStack&lt;Item&gt;: Stack {<br> private var objects: [Item] = []<br> <br> mutating func push(object: Item) {<br>   objects.append(object)<br> }<br> <br> mutating func pop() -&gt; Item? {<br>   return objects.popLast()<br> }<br> <br> func peek() -&gt; Item? {<br>   return objects.last<br> }<br>}<br> <br>//With MyStack, we can create a stack of any type.<br>var carStack = MyStack&lt;Car&gt;()<br>carStack.push(Car())</pre><p>This is great. Now we can create stacks of any type we want. What if we extend an existing class to conform to a protocol with an associated type? For example, extend the array to conform to Stack protocol. Here is how we can do it:</p><pre>extension Array: Stack {<br> mutating func push(object: Element) {<br>   self.append(object)<br> }<br> <br> mutating func pop() -&gt; Element? {<br>   return self.popLast()<br> }<br> <br> func peek() -&gt; Element? {<br>   return self.last<br> }<br>}</pre><p>Above, we are using the generic type Element of the Array as the associated type Object of the Stack protocol. The compiler infers that Array.Element == Stack.Object. Remember how Array and Stack is declared:</p><pre>public struct Array&lt;Element&gt; {…}<br>protocol Stack { <br> associatedtype Object <br> …<br>}</pre><h3>Protocols With Primary Associated Types</h3><p>What if we pass a stack of Work instance to a function? What happens if we write the code below? (keyword inout is to modify the stack that we pass, not related to our subject).</p><pre>func executeStack(stack: inout Stack) {<br>  ...<br>}</pre><p>We get this error:</p><pre>Use of protocol ‘Stack’ as a type must be written ‘any Stack’</pre><p>Here we can use any or some keywords. The difference between these is another subject. If we write it as some Stack it means something that conforms to the protocol Stack. Let’s try to call the functions like this:</p><pre>func executeStack(stack: inout some Stack) {<br> while let work = stack.pop() {<br>   work()<br> }<br>}</pre><p>For the code above, the compiler gives this error:</p><pre>Cannot call value of non-function type ‘(some Stack).Object’</pre><p>This is pretty understandable because the compiler has no idea that the items in this stack are ‘functions’ that it can call. To make it clear for the compiler, we need to declare it like this:</p><pre>func executeStack&lt;T: Stack&gt;(stack: inout T) where T.Object == Work {<br> while let work = stack.pop() {<br>   work()<br> }<br>}</pre><p>Above, we are telling the compiler that the parameter stack conforms to the Stack protocol, where its Object, is an instance of Work. This works, but it is a little ugly. We can also define it like this (with one condition):</p><pre>func executeStack(stack: inout some Stack&lt;Work&gt;){<br> while let work = stack.pop() {<br>   work()<br> }<br>}</pre><p>The condition is we need to declare our Stack protocol’s primary associated type, like this:</p><pre>protocol Stack&lt;Object&gt; {<br> associatedtype Object<br> …<br>}</pre><p>Above, Stack&lt;Object&gt; tells the compiler that Object is the primary associated type of the Stack protocol.</p><p>Let’s say we want to merge two stacks. Here is how we can declare a function that does that:</p><pre>func merge&lt;Item&gt;(stack1: some Stack&lt;Item&gt;, <br> stack2: some Stack&lt;Item&gt;) -&gt; some Stack&lt;Item&gt; {<br> …<br> return mergedStack<br>}</pre><h3>Extensions With Where Clauses</h3><p>We used a where clause in the example above, which is unnecessary because we have a better alternative of using primary associated type, where clauses are needed for contextual extensions.</p><p>Let’s say we want to write an extension to our MyStack to add functionality to encode itself. Maybe we want to save it to the disk. To encode, the stack and its items must conform to the Encodable protocol. Here is how we define it:</p><pre>extension MyStack: Encodable where Item: Encodable {<br> func encode() -&gt; Data? {<br>   try? JSONEncoder().encode(self)<br> }<br>}</pre><p>As you see, we used the where clause to restrict the associated type to being encodable. So, this extension only applies to MyStack instances in which they and their items are encodable. For all others, this extension doesn’t exist.</p><p>For example, because String conforms to the Encodable protocol, we can use it like this:</p><pre>var stringStack = MyStack&lt;String&gt;()<br>stringStack.push(object: “a string”)<br>print(stringStack.encode())</pre><pre>prints: Optional(20 bytes)</pre><p>Sometimes, instead of conforming to a protocol, we might need the associated type to be a specific type. For example, if we want to write an extension only for stacks that have Work as the associated type, this is how we can declare something like that:</p><pre>extension MyStack where Item == Work {<br> mutating func execute() {<br>   while let work = self.pop() {<br>     work()<br>   }<br> }<br>}</pre><p>Starting with Swift 5.7, it is also possible to write this by using angle brackets:</p><pre>extension MyStack&lt;Work&gt; {<br> mutating func execute() {<br>   while let work = self.pop() {<br>     work()<br>   }<br> }<br>}</pre><p>We can have multiple restrictions with where clauses. Something like this:</p><pre>extension Foo where T: Sequence, T.Element == Character {<br> func specialCaseFoo() { … }<br>}</pre><h3>Generic Type Aliases</h3><p>Generic typealiases allow you to provide a name for an existing nominal generic type or a name for a non-nominal type (e.g., tuples, functions, etc.) with generic parameters.</p><pre>typealias StringDictionary&lt;T&gt; = Dictionary&lt;String, T&gt;<br>typealias DictionaryOfStrings&lt;T : Hashable&gt; = Dictionary&lt;T, String&gt;<br>typealias IntFunction&lt;T&gt; = (T) -&gt; Int<br>typealias Vec3&lt;T&gt; = (T, T, T)<br>typealias BackwardTriple&lt;T1,T2,T3&gt; = (T3, T2, T1)</pre><h3>Implementation Details</h3><p>You can watch <a href="https://www.youtube.com/watch?v=ctS8FzqcRug">this</a> video for the implementation details of Generics in Swift.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cd549c53075" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/generics-in-swift-2cd549c53075">Learn Generics in Swift</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hello World iOS App Tutorial with Bazel]]></title>
            <link>https://medium.com/@tahabebek/hello-world-ios-app-with-bazel-bfc6cf710501?source=rss-249a73a3316f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfc6cf710501</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[bazel]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Taha Bebek]]></dc:creator>
            <pubDate>Mon, 05 Sep 2022 20:47:27 GMT</pubDate>
            <atom:updated>2024-03-05T19:00:13.638Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h1hqS8hKXLSCwJTsQAU1eQ.png" /></figure><blockquote>Build better</blockquote><blockquote>Rebuild only what is necessary. Get fast, incremental builds with Bazel’s advanced local and distributed caching, optimized dependency analysis, and parallel execution.</blockquote><blockquote>Simply scalable</blockquote><blockquote>Scale your organization, codebase, and Continuous Integration systems. Bazel handles codebases of any size, whether in multiple repositories or a huge monorepo.</blockquote><p>In this tutorial we will create a minimal app without using Xcode. We will add and edit files for the app on Visual Studio Code. We will build, run and test with Bazel.</p><h3>Download VSCode</h3><p>Download VSCode and install “Bazel“ extension.</p><h3>Create the project</h3><p>Create a folder named “BazelHelloWorld“. Open this folder in Visual Studio Code. To setup a minimal app, create 5 files in the structure below, .gitignore, BazelHelloWorldApp.swift, ContentView.swift, Info.plist and BazelHelloWorldTests.swift.</p><pre>BazelHelloWorld<br>│   .gitignore    <br>│<br>└───BazelHelloWorld<br>│   │   BazelHelloWorldApp.swift<br>│   │   ContentView.swift<br>│   │   Info.plist<br>│   │<br>│   <br>└───BazelHelloWorldTests<br>    │   BazelHelloWorldTests.swift<br></pre><p><strong>.gitignore</strong></p><pre>/bazel-BazelHelloWorld<br>/bazel-bin<br>/bazel-out<br>/bazel-testlogs<br>/bazel-bep.json<br>/bazel-explain.txt</pre><pre>.DS_STORE<br>xcuserdata/</pre><p><strong>BazelHelloWorldApp.swift</strong></p><pre>import SwiftUI</pre><pre>@main<br>struct BazelHelloWorldApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>        }<br>    }<br>}</pre><p><strong>ContentView.swift</strong></p><pre>import SwiftUI</pre><pre>struct ContentView: View {<br>    var body: some View {<br>        Text(&quot;Hello, world!&quot;)<br>            .padding()<br>    }<br>}</pre><p><strong>Info.plist</strong></p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;<br>&lt;plist version=&quot;1.0&quot;&gt;<br>&lt;dict&gt;<br>	&lt;key&gt;CFBundleDevelopmentRegion&lt;/key&gt;<br>	&lt;string&gt;$(DEVELOPMENT_LANGUAGE)&lt;/string&gt;<br>	&lt;key&gt;CFBundleExecutable&lt;/key&gt;<br>	&lt;string&gt;$(EXECUTABLE_NAME)&lt;/string&gt;<br>	&lt;key&gt;CFBundleIdentifier&lt;/key&gt;<br>	&lt;string&gt;$(PRODUCT_BUNDLE_IDENTIFIER)&lt;/string&gt;<br>	&lt;key&gt;CFBundleInfoDictionaryVersion&lt;/key&gt;<br>	&lt;string&gt;6.0&lt;/string&gt;<br>	&lt;key&gt;CFBundleName&lt;/key&gt;<br>	&lt;string&gt;$(PRODUCT_NAME)&lt;/string&gt;<br>	&lt;key&gt;CFBundlePackageType&lt;/key&gt;<br>	&lt;string&gt;$(PRODUCT_BUNDLE_PACKAGE_TYPE)&lt;/string&gt;<br>	&lt;key&gt;CFBundleShortVersionString&lt;/key&gt;<br>	&lt;string&gt;1.0&lt;/string&gt;<br>	&lt;key&gt;CFBundleVersion&lt;/key&gt;<br>	&lt;string&gt;1&lt;/string&gt;<br>	&lt;key&gt;LSRequiresIPhoneOS&lt;/key&gt;<br>	&lt;true/&gt;<br>	&lt;key&gt;UIApplicationSupportsIndirectInputEvents&lt;/key&gt;<br>	&lt;true/&gt;<br>	&lt;key&gt;UISupportedInterfaceOrientations&lt;/key&gt;<br>	&lt;array&gt;<br>		&lt;string&gt;UIInterfaceOrientationPortrait&lt;/string&gt;<br>	&lt;/array&gt;<br>&lt;/dict&gt;<br>&lt;/plist&gt;</pre><p><strong>BazelHelloWorldTests.swift</strong></p><pre>import XCTest<br>@testable import BazelHelloWorld</pre><pre>class BazelHelloWorldTests: XCTestCase {</pre><pre>    func testExample() throws {<br>        XCTFail()<br>    }<br>}</pre><h3>Install baselisk and buildifier on your machine.</h3><pre>brew install bazelisk<br>brew install buildifier</pre><h3>About Bazelisk</h3><p><a href="https://github.com/bazelbuild/bazelisk">Bazelisk</a> is a wrapper for Bazel written in Go. It automatically picks a good version of Bazel given your current working directory, downloads it from the official server (if required) and then transparently passes through all command-line arguments to the real Bazel binary. You can call it just like you would call Bazel.</p><h3>About Buildifier</h3><p><a href="https://github.com/bazelbuild/buildtools/tree/master/buildifier">Buildifier</a> is a tool for formatting bazel BUILD and .bzl files with a standard convention.</p><h3>Add .bazelversion file</h3><p>Bazelisk will build the project with a Bazel version specified in the .bazelversion file. We will check in that file into our version control to ensure reproducibility of our builds.</p><p>Add the following line to it (replace with latest release if needed) :</p><pre>5.1.1</pre><h3>Create the WORKSPACE.bazel file</h3><p>A <em>workspace</em> is a directory on your filesystem that contains the source files for the software you want to build. Each workspace directory has a text file named WORKSPACE.bazel which may be empty, or may contain references to <a href="https://bazel.build/docs/external">external dependencies</a> required to build the outputs.</p><p>Directories containing a file called WORKSPACE.bazel are considered the root of a workspace.</p><p>Add the following lines to the Workspace.BAZEL file (from <a href="https://github.com/bazelbuild/rules_apple/tree/f422d9f98e4f37b9740e7fda97b5e9bbebf3edb7#quick-setup_">rules_apple</a>):</p><pre>load(&quot;@bazel_tools//tools/build_defs/repo:http.bzl&quot;, &quot;http_archive&quot;)</pre><pre>http_archive(<br>    name = &quot;build_bazel_rules_apple&quot;,<br>    sha256 = &quot;4161b2283f80f33b93579627c3bd846169b2d58848b0ffb29b5d4db35263156a&quot;,<br>    url = &quot;https://github.com/bazelbuild/rules_apple/releases/download/0.34.0/rules_apple.0.34.0.tar.gz&quot;,<br>)</pre><pre>load(<br>    &quot;@build_bazel_rules_apple//apple:repositories.bzl&quot;,<br>    &quot;apple_rules_dependencies&quot;,<br>)</pre><pre>apple_rules_dependencies()</pre><pre>load(<br>    &quot;@build_bazel_rules_swift//swift:repositories.bzl&quot;,<br>    &quot;swift_rules_dependencies&quot;,<br>)</pre><pre>swift_rules_dependencies()</pre><pre>load(<br>    &quot;@build_bazel_rules_swift//swift:extras.bzl&quot;,<br>    &quot;swift_rules_extra_dependencies&quot;,<br>)</pre><pre>swift_rules_extra_dependencies()</pre><pre>load(<br>    &quot;@build_bazel_apple_support//lib:repositories.bzl&quot;,<br>    &quot;apple_support_dependencies&quot;,<br>)</pre><pre>apple_support_dependencies()</pre><p>“load” is like an import statement. At line 1, it imports http_archive function from bazel_tools library.</p><p>At line 3, it uses http_archive to download rules_apple library from Github url and gives a name to this downloaded library as build_bazel_rules_apple It could give it a different name as well. At line 9, it imports apple_rules_dependencies function from the build_bazel_rules_apple library it just loaded. The rest of the code does the same for swift_rules_dependencies, swift_rules_extra_dependencies and apple_support_dependencies.</p><h3>Rules</h3><p>A <strong>rule</strong> defines a series of <a href="https://bazel.build/extending/rules#actions"><strong>actions</strong></a> that Bazel performs on inputs to produce a set of outputs, which are referenced in <a href="https://bazel.build/extending/rules#providers"><strong>providers</strong></a> returned by the rule’s <a href="https://bazel.build/extending/rules#implementation_function"><strong>implementation function</strong></a>.</p><h3>Create .bazelrc file</h3><p>Bazel accepts many options. Some options are varied frequently (for example, — subcommands) while others stay the same across several builds (such as — package_path). To avoid specifying these unchanged options for every build (and other commands), you can specify options in a configuration file, called .bazelrc. More info on <a href="https://bazel.build/run/bazelrc">bazelrc</a>.</p><p>Add the following options to .bazelrc file:</p><pre>build --ios_minimum_os=15.5<br>build --ios_simulator_device=&quot;iPhone 13&quot;<br>build --ios_simulator_version=15.5<br>build --xcode_version=13.4.1<br>build --verbose_failures</pre><h3>Create BUILD.bazel file for each module</h3><p>A BUILD file <strong>contains several different types of instructions for Bazel</strong>. The most important type is the build rule, which tells Bazel how to build the desired outputs, such as executable binaries or libraries. Lets create our first module. Under the BazelHelloWorld/BazelHelloWorld directory, create BUILD.bazel file and add the following:</p><pre>load(&quot;@build_bazel_rules_apple//apple:ios.bzl&quot;, &quot;ios_application&quot;)<br>load(&quot;@build_bazel_rules_swift//swift:swift.bzl&quot;, &quot;swift_library&quot;)</pre><pre>swift_library(<br>    name = &quot;SwiftLibrary&quot;,<br>    srcs = glob([<br>        &quot;*.swift&quot;,<br>    ]),<br>    data = glob([<br>        &quot;*.xcassets/**/*&quot;,<br>        &quot;*.lproj/**/*&quot;,<br>    ]),<br>    module_name = &quot;BazelHelloWorld&quot;,<br>    tags = [&quot;manual&quot;],<br>    visibility = [&quot;//visibility:public&quot;],<br>)<br><br>ios_application(<br>    name = &quot;App&quot;,<br>    bundle_id = &quot;com.XXX.BazelHelloWorld&quot;,<br>    families = [<br>        &quot;iphone&quot;,<br>        &quot;ipad&quot;,<br>    ],<br>    infoplists = [&quot;:Info.plist&quot;],<br>    minimum_os_version = &quot;15.5&quot;,<br>    visibility = [&quot;//visibility:public&quot;],<br>    deps = [&quot;:SwiftLibrary&quot;],<br>)</pre><p>Under the BazelHelloWorld/BazelHelloWorldTests directory, create BUILD.bazel file and add the following:</p><pre>load(&quot;@build_bazel_rules_apple//apple:ios.bzl&quot;, &quot;ios_unit_test&quot;)<br>load(&quot;@build_bazel_rules_swift//swift:swift.bzl&quot;, &quot;swift_library&quot;)</pre><pre>swift_library(<br>    name = &quot;SwiftLibrary&quot;,<br>    srcs = glob([<br>        &quot;*.swift&quot;,<br>    ]),<br>    tags = [&quot;manual&quot;],<br>    deps = [<br>        &quot;//BazelHelloWorld:SwiftLibrary&quot;,<br>    ],<br>)</pre><pre>ios_unit_test(<br>    name = &quot;BazelHelloWorldTests&quot;,<br>    families = [<br>        &quot;iphone&quot;,<br>        &quot;ipad&quot;,<br>    ],<br>    minimum_os_version = &quot;15.5&quot;,<br>    deps = [&quot;:SwiftLibrary&quot;],<br>)</pre><h3>Final Project Structure</h3><p>This should be the final project structure:</p><pre>BazelHelloWorld<br>│   .gitignore    <br>│   .bazelrc<br>│   .bazelversion<br>│   WORKSPACE.bazel<br>│<br>└───BazelHelloWorld<br>│   │   BazelHelloWorldApp.swift<br>│   │   ContentView.swift<br>│   │   Info.plist<br>│   │   BUILD.bazel<br>│   <br>└───BazelHelloWorldTests<br>    │   BazelHelloWorldTests.swift<br>    │   BUILD.bazel<br></pre><h3>Build the project from command line</h3><pre>bazel build //BazelHelloWorld:App</pre><p>If there is any error, run the following command to see a detailed information:</p><pre>bazel build //BazelHelloWorld:App --sandbox_debug</pre><h3>Run the app on the simulator</h3><pre>bazel run //BazelHelloWorld:App</pre><h3>Run tests</h3><pre>bazel test //BazelHelloWorldTests:BazelHelloWorldTests</pre><h3>Dependencies</h3><p>To see a graph of dependencies, run:</p><pre>bazel query  --notool_deps --noimplicit_deps &quot;deps(//BazelHelloWorld:App)&quot; --output graph</pre><p>Then, paste the text into <a href="http://www.webgraphviz.com/">GraphViz</a>.</p><h3>Generate Xcode Project</h3><p>XCHammer generates Xcode projects from bazel build files. First, pull XCHammer into the WORKSPACE file:</p><pre>http_archive(<br>    name = &quot;xchammer&quot;,<br>    sha256 = &quot;8436fdeb48e29e787594e85eab92de3fe00a84dbf0e0495e4e83df3e68ed7d47&quot;,<br>    urls = [ &quot;https://github.com/pinterest/xchammer/releases/download/v3.4.1.0/xchammer.zip&quot; ],<br>)</pre><p>Next, create an xcode_project target including targets:</p><pre>load(&quot;@xchammer//:xcodeproject.bzl&quot;, &quot;xcode_project&quot;)</pre><pre>xcode_project(<br>    name = &quot;XcodeProject&quot;,<br>    targets = [ &quot;//BazelHelloWorld:App&quot; ],<br>    paths = [ &quot;**&quot; ],<br>)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfc6cf710501" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>