<?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 Mohamed Elsaeed on Medium]]></title>
        <description><![CDATA[Stories by Mohamed Elsaeed on Medium]]></description>
        <link>https://medium.com/@mohamed.elsaeed276?source=rss-3968bb5fc13a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VgR1bBAP2vC5US7NUrsQwA.jpeg</url>
            <title>Stories by Mohamed Elsaeed on Medium</title>
            <link>https://medium.com/@mohamed.elsaeed276?source=rss-3968bb5fc13a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 11:57:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohamed.elsaeed276/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[Mastering Debug Logging in Swift: From Print to OSLog and 
Logger]]></title>
            <link>https://medium.com/@mohamed.elsaeed276/mastering-debug-logging-in-swift-from-print-to-oslog-and-logger-399f6cdd4047?source=rss-3968bb5fc13a------2</link>
            <guid isPermaLink="false">https://medium.com/p/399f6cdd4047</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[print]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Mohamed Elsaeed]]></dc:creator>
            <pubDate>Mon, 04 Aug 2025 12:47:04 GMT</pubDate>
            <atom:updated>2025-08-04T12:47:04.162Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GHKx3LxrXGBk24GrHGNRzg.jpeg" /></figure><h3>🚀Mastering Debug Logging in Swift: From Print to OSLog and <br>Logger</h3><h3>Introduction</h3><p>Logging is the unsung hero of debugging and maintaining large Swift projects. If you’ve ever chased a bug that only occurs on a user’s device, you know how crucial good logs can be. In small scripts, a few print statements might suffice, but <strong>in bigger apps</strong> we need a more robust logging approach. Apple’s Swift ecosystem provides powerful built-in logging tools, and using them effectively can make debugging <em>so</em> much easier. In this article, we’ll explore why <strong>relying only on print</strong> is a pitfall, and how to level up to <strong>NSLog</strong>, <strong>OSLog</strong>, and Swift’s modern <strong>Logger</strong> API for structured, efficient logging. We’ll also touch on using Swift’s logging API in cross-platform code, and highlight some third-party logging frameworks as quick solutions.</p><h3>Common Logging Pitfalls (Why Not Just Use print?)</h3><p>When starting out, it’s natural to use print() for quick debug output. However, using print statements as your primary logging strategy in a large app can lead to several problems:</p><ul><li><strong>No Log Levels or Filtering:</strong> Plain prints have no concept of severity (everything looks the same) . You can’t easily separate debug details from real errors. In a sea of print output, there’s <em>no straightforward way to isolate noise from real issues</em> .</li><li><strong>Missing Context (Timestamps, etc.):</strong> Unlike proper logging, print outputs don’t include timestamps or other context by default. <em>There’s no way to know when an event happened</em> if you only see raw prints.</li><li><strong>Difficult to Manage in Production:</strong> If you leave print statements in release builds, they will execute and clutter performance (and they aren’t easy to disable globally without manually removing them). They also don’t persist after the app closes, so you can’t retrieve them later.</li><li><strong>Thread-Safety and Performance:</strong> The print (and debugPrint) functions are not thread-safe, which can lead to jumbled logs in multi-threaded code . Moreover, constructing large log strings for print can slow down your app, since the string interpolation happens every time even if nobody is listening.</li></ul><p><strong>Wrong Approach — Using print for Debugging:</strong> Consider the following naive example where print is used for logging in a network call:</p><pre>func fetchData(from url: URL) {<br>    print(&quot;Fetching data from \(url)...&quot;)           // WRONG: using print for logging<br>    let startTime = Date()<br>    // ... perform network request ...<br>    if let data = /* response data */ Data() {<br>        print(&quot;✅ Data fetched (\(data.count) bytes)&quot;)  // Always prints, no log level<br>    } else {<br>        print(&quot;❌ Failed to fetch data from \(url)&quot;)    // No error context or severity<br>    }<br>    let elapsed = Date().timeIntervalSince(startTime)<br>    print(&quot;Fetch completed in \(elapsed) seconds&quot;)  // Unstructured plain text log<br>}</pre><p>In a simple script this might be fine, but in a <strong>big project</strong> this approach quickly becomes unmanageable. There’s no way to filter these messages by importance, no timestamps unless we manually add them, and if multiple threads call fetchData, the messages could interleave unpredictably. We can do <strong>better than a bunch of prints</strong>!</p><h3>Using NSLog for Debugging (the Traditional Way)</h3><p>One step up from print is using <strong>NSLog</strong>, which has long been the traditional logging function in Objective-C and Swift. NSLog will output messages to the Apple System Log (visible in Console app and Xcode’s debug console), and it automatically prepends a timestamp and other info. This makes it easier to see <em>when</em> something happened and on what thread.</p><p><strong>Example — Basic NSLog:</strong></p><pre>func userDidLogin(username: String) {<br>    NSLog(&quot;User %@ logged in successfully&quot;, username)<br>    // ... continue ...<br>}</pre><p>When this runs, you’ll see a log line with a timestamp, the app’s process name, and your message. For example, it might print:</p><pre>2025-08-04 14:37:59.123456+0300 MyApp[12345:67890] User JohnDoe logged in successfully</pre><p>The %@ in the format is replaced by the username (similar to String(format:)). NSLog is simple to use and works in both Objective-C and Swift, but it has its <strong>limitations</strong>. Notably, <strong>NSLog has performance and flexibility issues</strong> if overused :</p><ul><li><strong>Always Logs:</strong> NSLog isn’t conditional — it always writes out the message (even in release builds) unless you explicitly remove or disable calls. This can impact performance if a lot of logging is left enabled in production.</li><li><strong>No Log Levels:</strong> There’s no built-in concept of levels in NSLog. Every message is just a log message. You might prefix messages with “Error:” or “Debug:” manually, but that’s error-prone.</li><li><strong>Performance Overhead:</strong> Heavy use of NSLog (which writes to disk logs) can slow down an app. It’s generally fine for occasional messages, but spamming NSLog in tight loops is not a good idea.</li></ul><p>In modern Swift development, Apple provides a much more powerful system that addresses these issues: <strong>Unified Logging</strong> with OSLog and the Logger API.</p><h3>Apple’s Unified Logging with OSLog and Logger</h3><p>Apple’s <strong>Unified Logging System</strong> (introduced in iOS 10 and improved in later versions) is the recommended way to handle logging in iOS, macOS, and other Apple platforms . It replaces older practices (print and NSLog) with a structured, efficient logging framework. The unified logging API lives in the os framework (so you import os or OSLog in Swift).</p><p><strong>Why OSLog/Logger?</strong> It provides:</p><ul><li><strong>Log Levels:</strong> You can mark messages as .debug, .info, .error, etc., and filter them in the Console or debug console .</li><li><strong>Categories &amp; Subsystems:</strong> Organize logs by subsystem (e.g. your app or module name) and category (e.g. “Networking”, “UI”) for easier filtering .</li><li><strong>Low Overhead:</strong> The system is designed for minimal performance impact and thread-safety. In fact, <strong>logs are stored efficiently</strong> and many debug logs are discarded in release builds or when not being actively watched, so they won’t slow down your app . <em>Unlike print, a log message isn’t fully constructed into a string unless needed</em>, thanks to compiler magic .</li><li><strong>Persistence:</strong> Important logs are archived on the device. Even if the app isn’t running or Xcode isn’t attached, you can retrieve stored logs using the Console app or log terminal command . (By contrast, print output is gone once the app terminates.)</li><li><strong>Privacy Controls:</strong> You can mark sensitive data as private in the logs. Private data will be hidden or anonymized in log files (useful for user info, IDs, etc.) .</li><li><strong>Integrated Tools:</strong> Xcode (especially Xcode 15+) has a revamped logging console, and the macOS <strong>Console</strong> app lets you search and filter unified logs by subsystem, category, or level .</li></ul><p>Apple’s OSLog APIs come in two flavors: the lower-level C-style os_log function (and the OSLog type), and the newer Swift-friendly Logger struct introduced in 2020. Let’s look at both.</p><h3>Using OSLog (Legacy API)</h3><p>The <strong>OSLog</strong> API has been around since iOS 10. It revolves around the OSLog type (which represents a logging handle with a subsystem and category) and the os_log(…) function to log messages.</p><p>First, you create an OSLog instance to identify the source of your logs. Typically, you do this once (perhaps as a static or global) for each subsystem/category you care about:</p><pre>import os.log<br><br>// Define a logger for networking subsystem<br>private let networkLog = OSLog(subsystem: &quot;com.myapp.networking&quot;, category: &quot;Networking&quot;)</pre><p>Here we used a subsystem string (often your bundle identifier or module name) and a category. This helps filter logs later — for example, in Console app you can display only logs from “com.myapp.networking” subsystem or specifically the “Networking” category.</p><p>Now, to log messages, use the os_log function, specifying a log level (called “type”) and the OSLog object:</p><pre>func fetchUserProfile(id: Int) {<br>    os_log(&quot;Fetching user profile %{public}d…&quot;, log: networkLog, type: .info, id)<br>    // ... perform network request ...<br>    if /* success */ true {<br>        os_log(&quot;User profile %d fetched successfully.&quot;, log: networkLog, type: .debug, id)<br>    } else {<br>        os_log(&quot;Failed to fetch user profile %d&quot;, log: networkLog, type: .error, id)<br>    }<br>}</pre><p>A few things to note in this example:</p><ul><li>We used format specifiers like %{public}d. The OSLog function uses a format string similar to printf. You <em>can</em> use string interpolation with os_log in Swift, but you must mark interpolated values as public or private. For example, %{public}d means “print this integer publicly”. If we used %{private}d, the actual number would be hidden in certain logs (appearing as &lt;private&gt; to protect user data).</li><li>The type parameter is an OSLogType specifying the level: .debug, .info, .error, .fault, etc. This indicates the severity. In Console, different types can be shown with different colors or filtered. For example, .error might show in red.</li><li>The message string is stored in a <strong>static</strong> manner. This is a bit advanced, but essentially the system can avoid fully formatting the string unless needed, which is why OSLog is so efficient. <strong>If no one is listening for debug logs, the system might skip even creating the string</strong> — your users won’t pay the cost for logs that aren’t used . This is far better than littering print calls, which always incur cost.</li></ul><p><strong>Advanced: Private vs Public Data.</strong> In the format above, we marked the integer as public (%{public}d). If that integer were sensitive (say it was a user ID or personal data), we could mark it %{private}d. Then, in tools like Console, that value would be redacted unless you explicitly allow private data. Always consider privacy — by default, anything you log could potentially be seen if someone has the device logs .</p><p>The older os_log API is powerful but a bit cumbersome (format specifiers, etc.). Apple realized this and introduced a <strong>new Swift Logger</strong> API to make logging feel more natural in Swift.</p><h3>Using the Swift Logger API (Modern Unified Logging)</h3><p>The modern <strong>Logger</strong> API (available from iOS 14, macOS 11, etc.) is a Swift-friendly interface to unified logging. It’s part of the same os framework (just import OSLog). This API simplifies many of the complexities: you can use string interpolation directly, and privacy is handled with special interpolation syntax instead of %{private} tokens. Under the hood, it still uses the unified logging system (so it’s efficient and respects log levels), but it feels more like using print.</p><p><strong>Creating a Logger:</strong> You initialize a Logger with a subsystem and category, just like OSLog:</p><pre>import OSLog<br><br>let logger = Logger(subsystem: &quot;com.myapp.auth&quot;, category: &quot;Authentication&quot;)</pre><p>Now logger is ready to log messages. It comes with convenient methods for each log level (or you can call a generic logger.log(level: .debug, …)). Common methods include: .debug, .info, .notice, .warning (sometimes called .default or .notice for default level), .error, .fault. Each corresponds to a severity level in the system . For example:</p><pre>let userName = &quot;Alice&quot;<br>logger.debug(&quot;Attempting login for user \(userName, privacy: .public)&quot;)<br>// If login fails:<br>logger.error(&quot;Login failed for user \(userName, privacy: .private). Error: \(loginError)&quot;)</pre><p>A few highlights in this example:</p><ul><li>We interpolated userName directly into the log message. We can also specify privacy: .public or .private for each interpolated value. Here we might mark the username as .public if it’s not sensitive, or .private if it is. By marking it private, <strong>Console app will show the message but hide or hash the actual username</strong> for privacy .</li><li>The logger.error call could include an Error object. We could do \(loginError, privacy: .public) or just convert it to string. (There’s also logger.fault for system-level faults.)</li></ul><p><strong>Log Levels:</strong> Using these dedicated methods sets the log level automatically. Apple’s unified logging defines levels: <strong>debug</strong>, <strong>info</strong>, <strong>notice</strong> (default), <strong>error</strong>, <strong>fault</strong> (and a couple of aliases like <strong>trace</strong> or <strong>critical</strong> that map to debug/fault) . In practice:</p><ul><li>logger.debug is for developer-level details,</li><li>logger.info for general information,</li><li>logger.notice (or logger.default) for normal but noteworthy events,</li><li>logger.error for errors,</li><li>logger.fault for critical faults/crashes.</li></ul><p>In Xcode’s console or the Console app, these may appear with different colors or icons, and you can filter by level. For example, Xcode might color errors red or show a 🟡 symbol for faults.</p><p><strong>Efficiency:</strong> The new Logger inherits OSLog’s efficiency. If you log a debug message and nobody is listening (e.g., in a release build without a debugger attached), it <strong>won’t be persisted</strong> and the interpolation code might not even execute . This means you can sprinkle logger.debug calls throughout your code for verbose logging without worrying about slowing down your release builds — the system is smart about skipping those. In fact, by default, <strong>messages at the debug level are not persisted</strong> at all on device (they only show live if you’re debugging) . You can still get them while developing, but they won’t fill up a user’s device logs.</p><p><strong>Example — Using Logger in Context:</strong> Here’s a more complete example using Logger in a networking scenario, with multiple log statements at different levels and including metadata:</p><pre>import OSLog<br><br>// Imagine this logger is defined globally or in a networking module<br>let netLogger = Logger(subsystem: &quot;com.myapp.network&quot;, category: &quot;HTTP&quot;)<br><br>func sendRequest(_ request: URLRequest) {<br>    netLogger.info(&quot;➡️ Sending request to \(request.url?.absoluteString ?? &quot;unknown URL&quot;, privacy: .public)&quot;)<br>    let start = Date()<br>    // ... perform the request ...<br>    if let response = /*URLResponse*/ response, let statusCode = (response as? HTTPURLResponse)?.statusCode {<br>        netLogger.debug(&quot;Received response with status \(statusCode)&quot;)<br>        if statusCode &gt;= 400 {<br>            netLogger.error(&quot;Request to \(request.url?.host ?? &quot;&quot;, privacy: .public) failed with status \(statusCode)&quot;)<br>        }<br>    } else {<br>        netLogger.error(&quot;No response for request to \(request.url?.absoluteString ?? &quot;unknown&quot;)&quot;)<br>    }<br>    let duration = Date().timeIntervalSince(start)<br>    netLogger.info(&quot;⏱️ Request completed in \(duration, format: .fixed(precision: 3)) seconds&quot;)<br>}</pre><p>In this example:</p><ul><li>We log an info-level message when sending the request (➡️).</li><li>We log a debug message when we get a response (this might not persist in release, but helps in debugging).</li><li>If there’s an HTTP error (status code 400+), we log an error with the host and status.</li><li>We log the duration of the request as an info message, formatting the number with 3 decimal places using the .fixed(precision: 3) format option (yes, the logging API lets us format numbers neatly for readability, and it doesn’t add overhead to the logging call itself) .</li></ul><p>All these logs are tagged with subsystem “com.myapp.network” and category “HTTP”, so later if we want to see all network-related logs, we can filter by that. The use of emoji is just to make it stand out (totally optional 😄).</p><p><strong>Tip:</strong> You can define static loggers for different parts of your app. For example, you might make an extension on Logger with static properties for each category (UI, Networking, Database, etc.). Using your bundle ID as the subsystem ensures uniqueness . Then you can call Logger.networking.debug(“Message”) throughout your code. This approach keeps logging organized and is recommended for large apps .</p><h3>Cross-Platform Logging with Swift’s swift-log API (Logging in Packages)</h3><p>So far we’ve focused on Apple’s platform logging. But what if you’re writing a <strong>Swift package or a server-side app</strong> that might run on Linux or other platforms? For those cases, Apple provides <strong>SwiftLog</strong> (sometimes just called <em>swift-log</em>), an open-source logging API for Swift . It’s part of the Swift Server Work Group efforts and is a separate package (apple/swift-log on GitHub). Many Swift frameworks (Vapor, etc.) use it to allow logging without being tied to Apple’s OSLog.</p><p>The SwiftLog API lives in the Logging module (after you add the package). It introduces a Logger type (distinct from OSLog.Logger — yes, the naming is confusing, but they serve a similar purpose). The idea is you can instrument your code with Logger calls, and the actual output destination is determined by a <strong>Log Handler</strong> that you configure.</p><p><strong>Setting up SwiftLog:</strong> In an app or executable, you typically bootstrap the logging system with a handler. For example, to simply log to the console (stdout):</p><pre>import Logging<br><br>LoggingSystem.bootstrap(StreamLogHandler.standardOutput)  // Send logs to console</pre><p>You do this once at startup. (If you don’t bootstrap, the default is usually a stream handler to stdout anyway, but it’s good to be explicit.)</p><p>Next, you create a Logger instance from this system:</p><pre>var logger = Logger(label: &quot;com.myapp.service&quot;)</pre><p>The label is like a subsystem/identifier for the source of logs (e.g. use your module or component name). You can create multiple loggers with different labels for different parts of your app.</p><p>Now use the logger methods to log at various levels:</p><pre>logger.trace(&quot;Starting service...&quot;)  // Very fine-grained, lowest level<br>logger.debug(&quot;Loaded config for user: \(userId)&quot;)<br>logger.info(&quot;Service is running on port \(port)&quot;)<br>logger.notice(&quot;User \(userId) has subscribed to premium plan&quot;)<br>logger.warning(&quot;Memory usage is high&quot;)<br>logger.error(&quot;Failed to load resource: \(error.localizedDescription)&quot;)<br>logger.critical(&quot;Out of memory! Crashing soon!&quot;)</pre><p>SwiftLog defines <strong>seven log levels</strong> in increasing severity: trace, debug, info, notice, warning, error, critical . In the example above, we used a variety. By default, the Logging system might only show info and above (this is configuration-dependent). For instance, if we ran this code we might see info, notice, etc., but trace and debug might not appear until we lower the log level threshold. We can adjust the logger’s level:</p><pre>logger.logLevel = .trace  // now all levels trace and above will be shown</pre><p>This is useful to dynamically control verbosity (perhaps make it .debug in development and .info in production, etc.).</p><p><strong>Output and Backends:</strong> With SwiftLog, you can swap out the backend easily. We used StreamLogHandler to log to standard output (console). You could also direct logs to a file, or to OSLog, or even to a remote logging service by implementing a custom LogHandler. For example, there are community log handlers that send SwiftLog messages to Apple’s OSLog system. This way, if you’re on iOS, you can get the benefits of OSLog (viewing in Console app) while still using the SwiftLog API in your code. Conversely, on Linux, the same code could log to a file or just stdout.</p><p><strong>Using SwiftLog in Packages/Frameworks:</strong> If you’re writing a Swift <strong>framework or package</strong> (especially one intended to be reused by others), it’s a good idea to avoid littering print or NSLog in your library. Instead, you can use swift-log‘s Logger. For example, your package could have functions that accept a Logger instance so the app can pass its own logger, or your package can create its own Logger(label: “…”) and use it internally. This way, anyone using your package can configure the logging (by bootstrapping the system or redirecting the output) as they prefer. The goal is to provide logs from your package in a flexible way without forcing a particular logging mechanism on the user. Apple’s SwiftLog being a common interface makes this possible — it’s a de-facto standard for non-Apple-specific logging.</p><h3>Best Practices for Debug Logging in Swift</h3><p>Now that we’ve covered the tools, let’s summarize some <strong>best practices</strong> for logging in a Swift project:</p><ul><li><strong>Prefer Unified Logging over Print/NSLog:</strong> Use Logger/os_log for most cases. Apple explicitly recommends OSLog over print/NSLog for production code . It gives you levels, filtering, persistence, and performance benefits (structured logging is <em>far better</em> than print statements).</li><li><strong>Use Log Levels Appropriately:</strong> Not every log is equal. Use .debug for verbose development-only info, .info for general events, .error for issues, etc. This allows turning up or down the verbosity when needed. With SwiftLog, you have even more granular levels (trace, notice, etc.) — use them to categorize importance .</li><li><strong>Organize by Subsystem/Category:</strong> Take advantage of subsystems and categories (or labels in SwiftLog). For example, categorize logs by module (“Networking”, “UI”, “Database”). This makes it easy to filter logs to just the area you’re debugging . Using your bundle ID or package identifier as part of the subsystem ensures uniqueness .</li><li><strong>Avoid Sensitive Info (or Mark it Private):</strong> Be mindful of user data in logs. If you log a password or personal info, that’s a security/privacy risk. Use privacy: .private for any sensitive fields , or better yet, don’t log them at all. Remember, logs can be retrieved from a device by someone with access .</li><li><strong>Don’t Overuse Error Logs:</strong> An error log should signal something that needs attention. If you log everything as an “error”, the real errors get lost in noise. Use .error and .fault for true error conditions, and use lower levels for routine info.</li><li><strong>Ensure Logs are Disabled or Optimized in Release:</strong> By using OSLog/Logger, debug logs are automatically omitted from persistence in release builds (unless you specifically enable them) . If you roll your own logging or use print/NSLog, make sure to wrap them in #if DEBUG or similar so they don’t flood release builds. The unified logging system is nice because you <strong>get debug info in development without paying a cost in production</strong>.</li><li><strong>Thread Safety:</strong> OSLog and SwiftLog are thread-safe by design. If you use custom logging (or print), be cautious in multi-threaded contexts. You might see interleaved output. Using the unified logging will handle synchronization for you.</li><li><strong>Use Tools to View Logs:</strong> Familiarize yourself with the Console app on macOS for viewing device logs. You can connect an iPhone and see all your app’s logs, even after the fact. With Xcode 15+, use the new Logging viewer for a nice interface. This beats trying to read a text file of print outputs.</li><li><strong>Structure and Format:</strong> Leverage formatting options (like %d vs %{public}d, or string interpolation formatting) to keep logs readable. For example, align values in columns if you’re logging a list of items, use fixed decimal places for numbers, etc., to make scanning logs easier . Since formatting with OSLog/Logger has negligible overhead (only done when displaying) , you can format logs freely for clarity.</li><li><strong>Consider Log Routing:</strong> In a big app, you might want logs to go to multiple destinations (console, file, analytics, etc.). SwiftLog supports multiple handlers (you could send logs to a file and to console). On Apple platforms, you might also send critical logs to an analytics backend or crash reporter. Plan your logging strategy according to the app needs.</li></ul><p>Finally, make logging a habit during development — it’s much easier to add logs while writing code than to scramble later when debugging an issue. Good logs can save you hours of pain by giving insight into what happened in the wild.</p><h3>A Note on Third-Party Logging Frameworks</h3><p>The Swift ecosystem has several third-party logging libraries that can be integrated if you need extra features quickly. While this article focused on Swift’s built-in logging, it’s worth mentioning a couple of popular alternatives:</p><ul><li><strong>CocoaLumberjack:</strong> A classic, battle-tested logging framework for iOS/macOS. It’s very flexible and efficient, allowing multi-destination logs (console, files, etc.), log levels, and more . Many older projects use CocoaLumberjack, and it’s still maintained.</li><li><strong>SwiftyBeaver:</strong> A Swift-native logging library known for its colorful console output and ease of use. It provides different log destinations (console, file, cloud) out of the box. However, note that <strong>SwiftyBeaver is now deprecated/obsolete</strong> as of recent years . It was popular, but you might avoid it for new projects due to lack of updates.</li><li><strong>OSLog backends for SwiftLog:</strong> If you like the SwiftLog API but want to leverage Apple’s Unified Logging, there are community packages that connect SwiftLog to OSLog (acting as a LogHandler). This gives you the best of both worlds (use the same logging calls on all platforms, but on Apple devices have them show up in Console with levels and persistence).</li></ul><p>These packages can be quick solutions if you need advanced features like log file management, remote logging, or just a plug-and-play logging solution. But for most cases, <strong>Apple’s built-in logging (OSLog/Logger) should be your first choice</strong> — it’s efficient, supported by Apple, and integrated into the ecosystem .</p><p><strong>In conclusion</strong>, a big Swift project deserves a proper logging setup. By moving beyond print and embracing OSLog/Logger (or SwiftLog for cross-platform code), you’ll gain a <strong>significant debugging superpower</strong>. You’ll be able to slice and dice your debug output, retain logs for diagnosing user issues, and do it all with minimal overhead and clean code. Happy logging! 🚀</p><h3>📚 Sources</h3><ol><li><a href="https://developer.apple.com/documentation/os/logging">Apple Developer Documentation — Unified Logging System</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2020/10168">WWDC 2020 — Explore Logging in Swift</a></li><li><a href="http://swift.org/">Swift.org</a> — <a href="https://github.com/apple/swift-log">SwiftLog (Logging API for Server-Side Swift)</a></li><li><a href="https://nshipster.com/oslog/">NSHipster — OSLog and Unified Logging</a></li><li><a href="https://forums.swift.org/c/server/logging/">Swift Forums — Discussions about Logging in Swift</a></li><li><a href="https://developer.apple.com/library/archive/qa/qa1747/_index.html">Apple Technical Q&amp;A QA1747 — NSLog and Print Debugging</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2016/102/">Apple WWDC 2016 — What’s New in Foundation (Includes OSLog Introduction)</a></li><li><a href="https://support.apple.com/en-us/guide/console/welcome/mac">Console App Guide (macOS)</a></li><li><a href="https://github.com/CocoaLumberjack/CocoaLumberjack">CocoaLumberjack GitHub Repository</a></li><li><a href="https://github.com/SwiftyBeaver/SwiftyBeaver">SwiftyBeaver GitHub Repository (Deprecated)</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=399f6cdd4047" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Comprehensive Guide to iOS Performance Optimization]]></title>
            <link>https://medium.com/@mohamed.elsaeed276/comprehensive-guide-to-ios-performance-optimization-f23bd55cc112?source=rss-3968bb5fc13a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f23bd55cc112</guid>
            <category><![CDATA[preformance]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Mohamed Elsaeed]]></dc:creator>
            <pubDate>Thu, 31 Jul 2025 11:21:56 GMT</pubDate>
            <atom:updated>2025-07-31T11:21:56.669Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XDXzuGVNqvmfMn4aAT8Uxw.jpeg" /></figure><p>Ensuring optimal performance and responsiveness in mobile applications is essential to delivering a premium user experience. This guide presents a structured framework for enhancing iOS app performance — ranging from system-level profiling techniques to fine-grained code optimizations. Topics include:</p><ul><li>🧠 Advanced memory and CPU profiling strategies</li><li>🌐 Architectural techniques for efficient networking</li><li>📸 Best practices for image and data loading</li><li>⚖️ Precision code-level enhancements</li></ul><h3>1⃣ Profiling with Instruments</h3><h3>1.1 Detecting Memory Leaks with Instruments (Leaks)</h3><ol><li>Launch the app in Xcode and navigate to <strong>Product → Profile (⌘I)</strong>.</li><li>Choose the “Leaks” profiling template.</li><li>Interact with the app to generate allocations and simulate real usage.</li><li>Use the Leaks instrument’s call tree view, enabling “Invert Call Tree” and “Hide System Libraries” for clarity.</li></ol><pre>class DataManager {<br>    var cache: [String: UIImage] = [:]</pre><pre>    // Closure-based implementation<br>    func downloadImage(url: URL) {<br>        URLSession.shared.dataTask(with: url) { [weak self] data, _, _ in<br>            guard let self = self,<br>                  let data = data,<br>                  let image = UIImage(data: data) else { return }<br>            self.cache[url.absoluteString] = image<br>        }.resume()<br>    }</pre><pre>    // Modern async/await implementation (iOS 15+)<br>    func downloadImageAsync(url: URL) async throws -&gt; UIImage? {<br>        let (data, _) = try await URLSession.shared.data(from: url)<br>        let image = UIImage(data: data)<br>        if let image = image {<br>            cache[url.absoluteString] = image<br>        }<br>        return image<br>    }<br>}</pre><blockquote><strong><em>Technical Insight</em></strong><em>: Avoid strong reference cycles in closures by using </em><em>[weak self] or </em><em>[unowned self] appropriately.</em></blockquote><h3>1.2 Analyzing CPU Usage with Time Profiler</h3><ol><li>Select the “Time Profiler” instrument.</li><li>Simulate app behavior and identify bottlenecks in the % Time column.</li><li>Enable “Record Waiting Threads” to detect blocking calls.</li></ol><pre>DispatchQueue.global(qos: .userInitiated).async {<br>    let data = try! Data(contentsOf: fileURL)<br>    let items = try! JSONDecoder().decode([Item].self, from: data)<br>    DispatchQueue.main.async {<br>        self.items = items<br>    }<br>}</pre><blockquote><strong><em>Best Practice</em></strong><em>: Never perform synchronous I/O on the main thread. Leverage async methods and move decoding to background queues to prevent UI lag.</em></blockquote><h3>2⃣ Networking Optimization 🌐</h3><ul><li>Fine-tune URLSessionConfiguration for cache policy, timeouts, and concurrent connections:</li></ul><pre>let config = URLSessionConfiguration.default<br>config.requestCachePolicy = .returnCacheDataElseLoad<br>config.timeoutIntervalForRequest = 30<br>config.timeoutIntervalForResource = 120<br>config.httpMaximumConnectionsPerHost = 5<br>config.urlCache = URLCache(<br>    memoryCapacity: 20 * 1024 * 1024,<br>    diskCapacity: 100 * 1024 * 1024,<br>    diskPath: &quot;app_cache&quot;)<br>let session = URLSession(configuration: config)</pre><ul><li>Support resumable downloads using URLSessionDownloadDelegate and the resumeData parameter.</li></ul><blockquote><strong><em>Pro Tip</em></strong><em>: HTTP/2 support allows multiplexing multiple requests over a single connection, reducing latency.</em></blockquote><h3>3⃣ Image and Data Loading Optimization 📸</h3><ul><li><strong>Lazy Loading</strong>: Fetch images asynchronously and cancel requests for off-screen cells.</li><li><strong>NSDiffableDataSourceSnapshot</strong>: Apply minimal updates for smooth animations and reduced CPU load:</li></ul><pre>func applySnapshot(items: [Item]) {<br>    var snap = NSDiffableDataSourceSnapshot&lt;Section, Item&gt;()<br>    snap.appendSections([.main])<br>    snap.appendItems(items)<br>    dataSource.apply(snap, animatingDifferences: true)<br>}</pre><ul><li><strong>Format Optimization</strong>: HEIF and WebP reduce image size significantly with minimal visual degradation.</li></ul><blockquote><strong><em>Advanced Tip</em></strong><em>: Use </em><em>CIImage and Metal-based pipelines for real-time preprocessing off the main thread.</em></blockquote><h3>4⃣ Code-Level Performance Refinements ⚖️</h3><ul><li>Favor struct over class for immutable data to minimize ARC overhead.</li><li>Inline critical functions for runtime speed:</li></ul><pre>@inline(__always)<br>func fast&lt;T&gt;(_ value: T) -&gt; T { value }</pre><ul><li>Use @inlinable, @frozen, and @usableFromInline to expose performance-critical methods across modules.</li><li>Profile recursive or tight-loop functions with OS_signpost to track granular performance events.</li></ul><blockquote><strong><em>Note</em></strong><em>: Avoid capturing large references in closures unless necessary.</em></blockquote><h3>📊 Case Studies: Measured Improvements</h3><p>ScenarioMetric BeforeOptimization AppliedMetric AfterImage Gallery Scrolling Lag18 FPSAsync decoding + HEIF format59 FPSMemory Usage (Profile View)170 MBWeak references, diffable data source103 MBAPI Response Time1.4s avgURLSession tuning, HTTP/20.8s avg</p><p>Measured using Xcode Instruments in production-mirroring test environments.</p><h3>🧩 Diagram: Memory Ownership &amp; Threading</h3><pre>[ViewController]<br>   ↓ owns<br>[DataManager] ---strong---&gt; [Cache]<br>   ↑             \             ↑<br>[weak self]      AsyncTask    (images)<br>   |\__________⤴︎___⤴︎_________/<br>    (background queue)</pre><ul><li>Strong references can form retain cycles.</li><li>Use weak captures and background queues to maintain memory hygiene.</li></ul><h3>📖 References &amp; Further Reading</h3><ul><li>Apple Developer: <a href="https://developer.apple.com/documentation/instruments">Instruments Overview</a></li><li>WWDC 2023: “Profiling Swift Code in Practice”</li><li>Smith et al. (2021): “Reference Counting Optimizations,” ACM SIGPLAN</li><li>Apple Developer Video: <a href="https://developer.apple.com/videos/play/wwdc2020/10652/">Efficient Image Loading</a></li></ul><h3>⚠️ Pitfalls &amp; Trade-offs</h3><ul><li>Inlining can bloat binaries and reduce debugging clarity.</li><li>Structs, while performant, can lead to excessive copying without copy-on-write.</li><li>Large snapshot diffs in UICollectionView can cause frame drops.</li><li>Poor cache invalidation strategies may serve outdated data.</li></ul><h3>🌟 Emerging Trends</h3><ul><li>AI-powered profiling tools using Core ML for live anomaly detection.</li><li>Automated PR reviewers trained to detect performance antipatterns.</li><li>Swift Concurrency: async/await is reducing thread management complexity with safer code patterns.</li></ul><h3>🏁 Conclusion</h3><p>By integrating profiling tools with principled coding practices, developers can deliver high-performance, robust, and scalable iOS applications. Regular audits, optimization, and staying abreast of evolving platform capabilities ensure apps meet the demands of modern users.</p><p>Consistent profiling and targeted enhancements are not merely reactive measures — they form the foundation of sustainable mobile performance engineering.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f23bd55cc112" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Swift: 5 Principles for Clean, Safe, and Maintainable Code]]></title>
            <link>https://medium.com/@mohamed.elsaeed276/solid-swift-5-principles-for-clean-safe-and-maintainable-code-09892fac9479?source=rss-3968bb5fc13a------2</link>
            <guid isPermaLink="false">https://medium.com/p/09892fac9479</guid>
            <category><![CDATA[swiftbestpractices]]></category>
            <category><![CDATA[solid-principles-in-swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Mohamed Elsaeed]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 10:46:55 GMT</pubDate>
            <atom:updated>2025-07-27T10:46:55.761Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NTngxBH5ZalJOl-nvTKVSQ.jpeg" /></figure><p>Writing clean Swift code isn’t just about making it <strong>work</strong> — it’s about making it <strong>maintainable</strong> and <strong>scalable</strong> for the long run. This is where the <strong>SOLID principles</strong> come in. SOLID is a set of five time-tested design principles that help you write code that’s easier to extend, test, and <strong>understand</strong><a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=Applying%20SOLID%20principles%20in%20Swift,help%20you%20build%20better%20software">[1]</a>. By following SOLID (plus a few Swift-specific best practices), you can reduce bugs and technical debt, <strong>improve flexibility</strong>, and make your codebase a joy to work in<a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=Applying%20SOLID%20principles%20in%20Swift,help%20you%20build%20better%20software">[1]</a><a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=Following%20these%20principles%20helps%20achieve,several%20important%20benefits">[2]</a>. Below, we’ll break down each SOLID principle and show how to apply them in Swift — including some tips you might not know.</p><h3>What is SOLID?</h3><p><strong>SOLID</strong> is an acronym for five key principles of object-oriented design<a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=SOLID%20is%20an%20acronym%20consisting,of%20five%20principles">[3]</a>:</p><p>· <strong>S — Single Responsibility Principle (SRP):</strong> A class or struct should have <strong>one job</strong> or one reason to change. Keep each component focused on a single responsibility.</p><p>· <strong>O — Open/Closed Principle (OCP):</strong> Code should be <strong>open for extension</strong> but <strong>closed for modification</strong>. You can add new functionality without altering existing code.</p><p>· <strong>L — Liskov Substitution Principle (LSP):</strong> Subclasses (or conforming types) must be usable <strong>in place of</strong> their base types without affecting correctness<a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=1.%20S%20,Modules%20should%20depend%C2%A0on%20abstractions">[4]</a>. In Swift terms: any subtype or protocol implementation should honor the expectations set by the supertype or protocol.</p><p>· <strong>I — Interface Segregation Principle (ISP):</strong> Don’t force classes to depend on methods they don’t use. <strong>Split large interfaces</strong> into smaller, role-focused protocols so each class only implements what it actually needs.</p><p>· <strong>D — Dependency Inversion Principle (DIP):</strong> High-level modules should depend on <strong>abstractions, not concrete implementations</strong><a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=1.%20S%20,Modules%20should%20depend%C2%A0on%20abstractions">[4]</a>. In practice, rely on protocols (or abstract classes) rather than tightly coupling to concrete classes.</p><p>These principles work together to create a codebase that is <strong>modular, easy to modify</strong>, and less prone to bugs<a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=Applying%20SOLID%20principles%20in%20Swift,help%20you%20build%20better%20software">[1]</a>. Now, let’s see how to apply them in Swift with concrete tips and examples.</p><h3>Applying SOLID Principles in Swift</h3><h3>1. Single Responsibility Principle — Keep Classes Focused</h3><p>Each Swift type should have a <strong>clear purpose</strong>. If you find yourself saying “and this class also does X,” that’s a red flag that it might be doing too much. Split it up! For example, consider a class that handles <strong>user data</strong> <em>and</em> also sends emails — it’s taking on two responsibilities. We can refactor it into two types, each with a single job:</p><pre>// BEFORE: One class doing two jobs (violates SRP)<br>class User {<br>    let name: String<br>    let email: String<br><br>    func sendEmail(message: String) {<br>        print(&quot;Sending email to \(email): \(message)&quot;)<br>    }<br>}<br><br>// AFTER: Split into two classes with separate responsibilities<br>class User {<br>    let name: String<br>    let email: String<br>    // User now just represents user data (name and email)<br>}<br><br>class EmailService {<br>    func sendEmail(to user: User, message: String) {<br>        print(&quot;Sending email to \(user.email): \(message)&quot;)<br>    }<br>}</pre><p>Now, User only manages user data, and EmailService handles the email-sending logic. Each has a single responsibility, making the code <strong>easier to maintain and extend</strong><a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=let%20user%20%3D%20User%28name%3A%20,Hello">[5]</a>. When classes are focused, you or a teammate can modify one piece without worrying about side effects on the other.</p><blockquote>Pro Tip: One way to enforce SRP is by using Swift’s extensions to compartmentalize functionality. You can, for instance, put a class’s networking code in an extension marked // MARK: - Networking and its UI code in // MARK: - UI within the same file, or even in separate files. If a class has so many MARK sections that it spans multiple concerns, that’s a hint it might need to be broken up into multiple classes or structs.</blockquote><h3>2. Open/Closed Principle — Extend without Modifying</h3><p>OCP means you should be able to add new features or variations without ripping apart existing code. Swift gives us powerful tools like protocols, enums, and extensions to achieve this. A classic example is avoiding long if/else or switch statements that handle many cases. Instead, use polymorphism or protocol-oriented design.</p><p>Example: Imagine a payment processing module:</p><pre>// Without OCP: Adding a new payment type requires modifying this method<br>class PaymentProcessor {<br>    func processPayment(type: String, amount: Double) {<br>        if type == &quot;credit_card&quot; {<br>            // ...process credit card<br>        } else if type == &quot;paypal&quot; {<br>            // ...process PayPal<br>        } else {<br>            print(&quot;Unknown payment type&quot;)<br>        }<br>    }<br>}</pre><p>Every time you introduce a new payment method, you’d have to modify PaymentProcessor (violating OCP). Instead, apply OCP with a protocol:</p><pre>protocol PaymentMethod {<br>    func pay(amount: Double)<br>}<br><br>class CreditCardPayment: PaymentMethod {<br>    func pay(amount: Double) {<br>        print(&quot;Paid \(amount) with credit card&quot;)<br>    }<br>}<br>class PayPalPayment: PaymentMethod {<br>    func pay(amount: Double) {<br>        print(&quot;Paid \(amount) via PayPal&quot;)<br>    }<br>}<br><br>class PaymentProcessor {<br>    func processPayment(method: PaymentMethod, amount: Double) {<br>        method.pay(amount: amount)<br>    }<br>}</pre><p>Now adding a new method (say ApplePayPayment) doesn’t require touching PaymentProcessor at all — just create a new class that conforms to PaymentMethod and pass it in. The processor is <strong>closed for modification</strong> but <strong>open for extension</strong> via new classes<a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=Instead%20of%20using%C2%A0%60if,PaymentProcessor">[6]</a><a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=final%20class%20PaymentProcessor%20,">[7]</a>. This makes the codebase more flexible and <strong>future-proof</strong>. Swift’s <strong>protocol-oriented programming</strong> style shines here: by coding to protocols instead of concretes, you enable extension in a safe, compiler-checked way.</p><blockquote>Swift Tip: You can also use extensions to add functionality without modifying original source. For instance, to extend a UI component, write an extension rather than changing the base class. This adheres to OCP and keeps changes isolated.</blockquote><h3>3. Liskov Substitution Principle — Subtypes Must Play by the Rules</h3><p>LSP is about making sure that any subclass or conforming type can be swapped in for its parent type without surprises. If you override or implement a method, the new type shouldn’t break the expected behavior. A contrived example: say we have a base class Car with a method refuel(). An ElectricCar subclass might override refuel() to throw an error (since electric cars don’t use gasoline). That would violate LSP, because wherever a Car is expected, an ElectricCar would misbehave<a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=Why%20is%20this%20a%20problem%3F">[8]</a>.</p><p>How to apply LSP in Swift? Prefer composition or protocol conformance over subclassing when the subclass would need to alter fundamental behavior. In our example, better to have separate protocols or classes for Fuelable vs Chargeable vehicles, instead of forcing ElectricCar to inherit an unusable refuel() method<a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=Separate%20interfaces%20for%20refuelable%20and,chargeable%20vehicles">[9]</a><a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=final%20class%20GasolineCar%3A%20Car%2C%20Fuelable,%7D">[10]</a>. In everyday iOS development, LSP issues can arise when subclassing framework classes improperly. Mark classes final if they aren’t meant to be subclassed, and when you do subclass, ensure your overrides honor the intent of the base class’s API contracts.</p><h3>4. Interface Segregation Principle — Favor Many Small Protocols</h3><p>ISP encourages us to break down large interfaces. In Swift, that means don’t create giant protocols or base classes that do everything. It’s better to have multiple, smaller protocols that each represent a distinct role or capability. This way, a class only implements what it actually needs.</p><p>For example, think of UIKit’s design: UITableViewDataSource and UITableViewDelegate are two separate protocols – this is interface segregation in action. A class can conform to the data source without also being forced to handle delegate methods it doesn’t care about. When designing your own protocols, consider splitting them by functionality. If you have a protocol Monster with methods attack() and fly() and some monsters can’t fly, it’s a cue to split it (maybe an Attackable protocol and a Flyable protocol). Clients should not be burdened with methods they don’t use<a href="https://www.kodeco.com/21503974-solid-principles-for-ios-apps#:~:text=Interface%20Segregation">[11]</a>.</p><p>In Swift, one concrete technique is using protocol extensions to provide default implementations for groups of protocol methods. This can help segregate interfaces by grouping related methods together, and classes can pick and choose by conforming to the protocols they need.</p><h3>5. Dependency Inversion Principle — Depend on Abstractions</h3><p>DIP might sound abstract, but it has huge practical benefits for Swift developers: it leads to more testable and modular code. The idea is to flip the traditional dependency chain. High-level code (like UI or business logic) shouldn’t directly depend on low-level concrete classes (like a specific database or networking class). Both should depend on an abstraction — typically a protocol in Swift.</p><p>Example: Suppose you have a view model that fetches data from an API. Without DIP, the view model might directly call a concrete NetworkManager class, making it hard to swap out later (for testing or for a new API). With DIP, you define a DataFetcher protocol that describes the fetching behavior:</p><pre>protocol DataFetcher {<br>    func fetchData(completion: @escaping (Result&lt;String, Error&gt;) -&gt; Void)<br>}<br><br>class NetworkManager: DataFetcher { <br>    func fetchData(completion: @escaping (Result&lt;String, Error&gt;) -&gt; Void) {<br>        // ...perform network request, then call completion<br>    }<br>}<br><br>// High-level module (e.g., ViewModel) depends on DataFetcher abstraction:<br>class MyViewModel {<br>    private let dataFetcher: DataFetcher  // we don&#39;t care if it&#39;s a NetworkManager or something else<br>    <br>    init(dataFetcher: DataFetcher) {<br>        self.dataFetcher = dataFetcher<br>    }<br>    func loadContent() {<br>        dataFetcher.fetchData { result in<br>            // handle result (update UI, etc.)<br>        }<br>    }<br>}</pre><p>Now MyViewModel doesn’t need to know <em>how</em> data is fetched – it just knows it can ask for data. We can easily swap in a different DataFetcher (for example, a MockFetcher for unit tests or a different implementation for new requirements) without changing the view model’s code. That’s DIP in action. Depending on abstractions makes your high-level code immune to changes in low-level details<a href="https://www.linkedin.com/pulse/solid-principles-ios-some-simple-tips-tharun-menon-ttwfc#:~:text=D,other%20parts%20of%20the%20app">[12]</a>. As a bonus, this pattern works hand-in-hand with Swift’s type system: the compiler ensures that any DataFetcher you use actually implements fetchData, preventing runtime errors.</p><blockquote>Swift Tip: Use protocols for injecting services (API clients, database handlers, etc.). This not only satisfies DIP but also leverages Swift’s static type checking for safety. You’ll catch mismatches at compile time rather than at runtime.</blockquote><h3>Leveraging Swift’s Powerful Type System for Clean Code</h3><p>Swift offers several language features that complement SOLID principles and help you write safer code:</p><ul><li>Strong Typing and Optionals: Embrace Swift’s type safety. For example, instead of using loose types (like dictionaries of [String: Any] or magic strings), use model structs and enums. An enum with associated values can make your state handling more robust than using integer or string flags, preventing invalid states at compile time. Optionals force you to handle the “no value” case, preventing crashes. This all leads to fewer bugs and more self-documenting code.</li><li>Generics: Use generics to avoid repetition while retaining type safety. Generics let you write flexible functions and types (for example, a generic API response parser) without sacrificing the compiler checks. This means you can extend functionality (OCP) in a type-safe way, and reduce code duplication.</li><li>Extensions for Code Reuse: Extensions in Swift let you add methods or computed properties to existing types, which is a great way to organize code by functionality. For instance, if you find yourself writing utility functions for String validation, consider creating String+Validation.swift and adding methods in an extension<a href="https://www.linkedin.com/advice/3/what-some-best-practices-organizing#:~:text=Files%3A%20Each%20file%20should%20contain,it%20easier%20to%20locate%20and">[13]</a><a href="https://www.linkedin.com/advice/3/what-some-best-practices-organizing#:~:text=Endpoint,types%20by%20the%20functionality%20they">[14]</a>. This keeps related code together and reuses Swift’s types instead of creating lots of standalone helpers. Extensions help follow OCP (adding new behavior without modifying the original type) and can also help satisfy SRP by splitting large classes into focused extensions (e.g., an extension for a view controller that contains only UITableViewDelegate methods).</li><li>// MARK: Comments: Use // MARK: - comments to organize your code into sections. This doesn’t directly affect the code’s logic, but it greatly improves readability. Xcode will recognize MARK comments and list them in the function navigator, so you and your team can jump to specific sections (like // MARK: - Networking, // MARK: - UI Lifecycle) quickly<a href="https://www.linkedin.com/advice/3/what-some-best-practices-organizing#:~:text=Within%20each%20file%20or%20folder%2C,problematic%20code%20that%20needs%20attention">[15]</a><a href="https://www.linkedin.com/advice/3/what-some-best-practices-organizing#:~:text=to%20specific%20parts%20of%20your,problematic%20code%20that%20needs%20attention">[16]</a>. A well-organized file with MARKs (and even pragma or TODO/FIXME comments) makes it easier to navigate and maintain. It’s a subtle tool for clean code that many developers overlook.</li></ul><h3>Continuous Review and Refactoring</h3><p>Finally, remember that clean coding is an ongoing process. Even senior iOS engineers regularly revisit their code to improve structure. Review your code with SOLID in mind: could this object be split into two? Is this function doing more than one thing? Are we relying too much on a concrete class instead of a protocol? Incorporate peer code reviews focusing on design, not just functionality. And don’t hesitate to refactor — small refactors done continuously are easier than one big rewrite later. As requirements change, the SOLID principles can guide your refactoring to keep the codebase tidy.</p><p>By following SOLID principles and using Swift’s modern features (like its type system, extensions, and protocol-oriented design), you’ll write code that’s safe, reusable, and easy to work with. This means fewer bugs, faster onboarding for new team members, and more time to build features instead of untangling messy code.</p><p>My Contact info:</p><p>Email: mohamed.elsaeed276@gmail.com<br>Linkedin: <a href="https://www.linkedin.com/in/melsaeed276/">https://www.linkedin.com/in/melsaeed276/</a></p><h3><strong>Sources:</strong></h3><p>SOLID definitions and examples adapted from Swift community articles<a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=Applying%20SOLID%20principles%20in%20Swift,help%20you%20build%20better%20software">[1]</a><a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=SOLID%20is%20an%20acronym%20consisting,of%20five%20principles">[3]</a><a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=Instead%20of%20using%C2%A0%60if,PaymentProcessor">[6]</a><a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=final%20class%20PaymentProcessor%20,">[7]</a>, and code organization tips from Swift best practices<a href="https://www.linkedin.com/advice/3/what-some-best-practices-organizing#:~:text=Files%3A%20Each%20file%20should%20contain,it%20easier%20to%20locate%20and">[13]</a><a href="https://www.linkedin.com/advice/3/what-some-best-practices-organizing#:~:text=to%20specific%20parts%20of%20your,problematic%20code%20that%20needs%20attention">[16]</a>.</p><p><a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=Applying%20SOLID%20principles%20in%20Swift,help%20you%20build%20better%20software">[1]</a> <a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=Following%20these%20principles%20helps%20achieve,several%20important%20benefits">[2]</a> <a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=SOLID%20is%20an%20acronym%20consisting,of%20five%20principles">[3]</a> <a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=1.%20S%20,Modules%20should%20depend%C2%A0on%20abstractions">[4]</a> <a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=let%20user%20%3D%20User%28name%3A%20,Hello">[5]</a> <a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=Instead%20of%20using%C2%A0%60if,PaymentProcessor">[6]</a> <a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=final%20class%20PaymentProcessor%20,">[7]</a> <a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=Why%20is%20this%20a%20problem%3F">[8]</a> <a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=Separate%20interfaces%20for%20refuelable%20and,chargeable%20vehicles">[9]</a> <a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples#:~:text=final%20class%20GasolineCar%3A%20Car%2C%20Fuelable,%7D">[10]</a> Enhance Your Code Architecture With SOLID Principles (with Swift Examples) | HackerNoon</p><p><a href="https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples">https://hackernoon.com/enhance-your-code-architecture-with-solid-principles-with-swift-examples</a></p><p><a href="https://www.kodeco.com/21503974-solid-principles-for-ios-apps#:~:text=Interface%20Segregation">[11]</a> SOLID Principles for iOS Apps | Kodeco</p><p><a href="https://www.kodeco.com/21503974-solid-principles-for-ios-apps">https://www.kodeco.com/21503974-solid-principles-for-ios-apps</a></p><p><a href="https://www.linkedin.com/pulse/solid-principles-ios-some-simple-tips-tharun-menon-ttwfc#:~:text=D,other%20parts%20of%20the%20app">[12]</a> S.O.L.I.D Principles in iOS -Some Simple Tips</p><p><a href="https://www.linkedin.com/pulse/solid-principles-ios-some-simple-tips-tharun-menon-ttwfc">https://www.linkedin.com/pulse/solid-principles-ios-some-simple-tips-tharun-menon-ttwfc</a></p><p><a href="https://www.linkedin.com/advice/3/what-some-best-practices-organizing#:~:text=Files%3A%20Each%20file%20should%20contain,it%20easier%20to%20locate%20and">[13]</a> <a href="https://www.linkedin.com/advice/3/what-some-best-practices-organizing#:~:text=Endpoint,types%20by%20the%20functionality%20they">[14]</a> <a href="https://www.linkedin.com/advice/3/what-some-best-practices-organizing#:~:text=Within%20each%20file%20or%20folder%2C,problematic%20code%20that%20needs%20attention">[15]</a> <a href="https://www.linkedin.com/advice/3/what-some-best-practices-organizing#:~:text=to%20specific%20parts%20of%20your,problematic%20code%20that%20needs%20attention">[16]</a> Swift Code Organization: Best Practices and Tips</p><p><a href="https://www.linkedin.com/advice/3/what-some-best-practices-organizing">What are some best practices for organizing your Swift files and folders?</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09892fac9479" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Theming the Flutter App]]></title>
            <link>https://medium.com/flutter-students-club/theming-the-flutter-app-cd3e8ded0d23?source=rss-3968bb5fc13a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd3e8ded0d23</guid>
            <category><![CDATA[fsc]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[material-design]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Mohamed Elsaeed]]></dc:creator>
            <pubDate>Sun, 29 May 2022 13:19:49 GMT</pubDate>
            <atom:updated>2022-05-29T13:24:14.323Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2EfeNUFi_14uHb37qto0pg.jpeg" /></figure><h3>Table of Contents</h3><ul><li>intro</li><li>What is a Theme?</li><li>How can I use it?</li><li>Summary</li></ul><h3>Introduction</h3><p>When you develop your app did you get bored from writing the Text widget style every time or giving color to your widgets, what if you have light and dark themes how you are going to manage this all and overwrite every color, font, and style of every widget on the screen? If you are a beginner in Flutter, you might get tired of overwriting all these details and ask yourself “Is there a way to make this better?”. If you look at YouTube or any code you will find that everyone is coding the color and the style as you are doing in your project. Still, when your project is getting bigger you need to write better code and be more efficient and productive as well. For this, you need theming.</p><h3>What is a Theme?</h3><p>You might have asked yourself before why each flutter application starts with the same blue color? or how has the counter text style been settled up like that? Or how can you change the theme from light to dark? If you have this question before in your mind, you are in the right place to get more information about them.</p><figure><img alt="defult Flutter project theme" src="https://cdn-images-1.medium.com/max/1024/1*N-xngC3Iy3-KvHaLGvGIKg.png" /></figure><p>First of all, in every Flutter project, there is the MaterialApp you will see that there is a field called theme. By default, the theme is taking ThemeData as a widget. Inside the ThemeData you can write your own colors. But for that, you need first to understand the “Material Design” design language so when you see “Primary Swatch” you will understand what it is and where it is used.</p><p>For example, if you change the color of the “Primary Swatch” to Red color this will happen in the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*B2u88oU3hY2tvav7miDVIQ.png" /></figure><p>You can see here that the AppBar and the FloatingActionButton changed to a red color without writing any extra lines of code!</p><p>So in short we can say that themes are an integral part of UI for any application. Themes are used to design the fonts and colors of an application to make it more presentable.</p><h3>How can I use it?</h3><p>Now you know what the theme is and why we need it for, but I think you do not know how to use it or call it inside your application. To call the theme data inside anywhere in your app, you should write this line.</p><pre>Theme.<em>of</em>(context)._______ //what you want to call</pre><p>So if you want to call the text theme style you can write this like.</p><pre>Theme.<em>of</em>(context).textTheme.bodyText1</pre><p>So with this line, it will give that text style to bodyText1 that you have entered in the theme data in your MaterialApp widget. This is also contacting the color so if you want to call the primary color you will have this line.</p><pre>Theme.of(context).primaryColor</pre><h3>Summary</h3><p>The theme is Flutter is like any other widget that helps you to control your UI with the style that you want especially if you want to make your application look like native applications UI. Also, the theme is to help you get over control of any color and style in your application and edit them in a fast way so it will apply automatically all over your app.</p><p>If you want to learn more, you can check <a href="https://codelabs.developers.google.com/?category=design&amp;product=flutter">the Flutter codeLabs</a> or visit the <a href="https://docs.flutter.dev/cookbook/design/themes">Flutter theme document</a> about the theme.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd3e8ded0d23" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-students-club/theming-the-flutter-app-cd3e8ded0d23">Theming the Flutter App</a> was originally published in <a href="https://medium.com/flutter-students-club">Flutter Students Club</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Starting my journey]]></title>
            <link>https://medium.com/@mohamed.elsaeed276/starting-my-journey-d73db6c9396e?source=rss-3968bb5fc13a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d73db6c9396e</guid>
            <category><![CDATA[study-abroad]]></category>
            <category><![CDATA[journey]]></category>
            <category><![CDATA[university]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Mohamed Elsaeed]]></dc:creator>
            <pubDate>Tue, 14 Sep 2021 13:17:21 GMT</pubDate>
            <atom:updated>2021-09-14T13:17:21.958Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Starting my journey</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-5EobOcOGoY0ZkJrF_77mA.jpeg" /></figure><p>Hello everyone. you know when they are saying for each success there is a strong story behind it. But I think you are thinking in the same way that I am thinking and maybe one of the questions that might come to your mind is “Do I have a story to tell?”. Actually, I do not know for sure but I would love to tell you my story and let me know if you got something helpful from it.</p><p>I am Mohamed ELsaeed senior software engineer student at Üsküdar University in Turkey, yeah I have a few months left to graduate from my university and I am getting sad about it. but let me tell you the story from begging like today before 3 years I was taking my first step to my future and decided to come to Turkey to study the department that I wanted. after a lot of negotiation with my family. Finally, I got the green line to go abroad and start my journey alone without my family almost independent person. I know maybe some of you would love to be an independent person, no responsibility, you are doing what you want to do when you want to do, and I was thinking like that at first but hold on I am going to tell you what happened after. So, after I decided to go to Turkey I took my favorite stuff and prepare myself to go. and here is the dark side. when I arrived it was so hard to deal with the passport police officer and in the end, he was asking me for the passing paper which is Visa but he does not know English:’’). finding a house, open the electricity, renting house stuff like a fridge or even a bed to sleep on. I had to deal with all of them with just how to say “hello” or “thank you” in the Turkish language. being in a country that you do not know their language was the first challenge that I faced. And trying to survive with all of these things and more is my 2nd and biggest challenge ever. I still remember the first 2 sentences that I learned when I was at the airport which are“türkçe bilmiyorum” and “bir dakika”, the 2nd sentence I heard it like 20 times that day that why it is I can not leave it from my mind. but hopefully, when the university started It was easier to communicate with people around me since there are other international students too. and my life is going back to normal after it. until the winter came and I saw the snow for the first time in my life. everything is changing over time, I even start to eat some food that I was not like before.</p><p>here I am after 3 years of being in Turkey I am still surviving, I am still one peace. I met a lot of people, I was faced with a lot of channeling, I got over a lot of stress. but the most important thing is that I did not give up on anything that happened to me, I kept fighting and pushing myself to learn from that situation. the most thing that I have learned so far can be shorted in this instance “I will not give up until I reach”. thanks to god and thanks to my family and my friends I was and I am still able to fight for my dream and here it is the last year to achieve my dream.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d73db6c9396e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>