Are you over 18 and want to see adult content?
More Annotations
A complete backup of https://namedclothing.com
Are you over 18 and want to see adult content?
A complete backup of https://topsify.com
Are you over 18 and want to see adult content?
A complete backup of https://skoda-auto.it
Are you over 18 and want to see adult content?
A complete backup of https://fundresearch.de
Are you over 18 and want to see adult content?
A complete backup of https://ntkernel.com
Are you over 18 and want to see adult content?
A complete backup of https://friendsofthelegacytrail.org
Are you over 18 and want to see adult content?
A complete backup of https://sambadenglish.com
Are you over 18 and want to see adult content?
A complete backup of https://draftify.net
Are you over 18 and want to see adult content?
A complete backup of https://mlmtokenizer.com
Are you over 18 and want to see adult content?
A complete backup of https://fishin.com
Are you over 18 and want to see adult content?
A complete backup of https://magicalomaha.com
Are you over 18 and want to see adult content?
A complete backup of https://dentalspecialty.com
Are you over 18 and want to see adult content?
Favourite Annotations
Drone CI – Automate Software Testing and Delivery
Are you over 18 and want to see adult content?
Unsecured | Careers, Surveys, Bill Pay & Finance Tips
Are you over 18 and want to see adult content?
Buy Sale Rent. Largest real estate marketplace in Bangladesh | pbazaar.com
Are you over 18 and want to see adult content?
Download Film Indonesia Terbaru 2019
Are you over 18 and want to see adult content?
WordPress.com — Get a Free Blog Here
Are you over 18 and want to see adult content?
Resumes Mag | Resume Templates Service
Are you over 18 and want to see adult content?
Text
versions
THE POWER OF KEY PATHS IN SWIFT The basics. Key paths essentially let us reference any instance property as a separate value. As such, they can be passed around, used in expressions, and enable a piece of code to get or set a property without actually knowing which exact property its working with. FORMATTING NUMBERS IN SWIFT Solving the decimal problem. At the most basic level, creating a textual representation of a given number simply involves initializing a String with it, which can either be done directly, or by using a string literal:. let a = String (42) // "42" let b = String (3.14) // "3.14" let c = " \(42), \(3.14) " // "42, 3.14". However, while that approach might work well for generating simpler CREATING CUSTOM SWIFTUI CONTAINER VIEWS Although SwiftUI ships with a quite large number of built-in container views, such as VStack, HStack and List, sometimes we might also want to define our own custom containers as well.. For example, let’s say that we’re working on an app that features a carousel-like component, which lets our users scroll through a horizontal list of items. That component is currently implemented like this: INTEGRATION TESTS IN SWIFT The integration of multiple units. Any code base can usually be separated into different parts — both by high-level features, such as Search, Login, Networking, and so on — and at a much lower level, by looking at individual classes and functions.A common way to test all those different parts is to do unit testing, and test each part (or unit) in isolation. BUILDING CUSTOM COMBINE PUBLISHERS IN SWIFT Building custom Combine publishers in Swift. Apple’s Combine framework provides a general-purpose abstraction for asynchronous programming, by enabling various values and events to be emitted, transformed and observed over time. Within the world of Combine, an object that emits such asynchronous values and events is called apublisher, and
REFLECTION IN SWIFT
Reflection is a common programming language feature that enables us to inspect, and work with, the members of a type — dynamically, at runtime. That may seem at odds with Swift’s heavy focus on compile-time validation — but this week, let’s take a look at when reflection can come in handy, and how it can let us make our code abit more dynamic.
OBSERVERS IN SWIFT
Observers in Swift - Part 1. observers. design patterns. Swift 5.0. Published on 15 Apr 2018. Often when building apps, we find ourselves in situations when we need to set up a one-to-many relationship between objects. It can be when multiple objects want to react to changes in the same state, or when a certain event needs to bebroadcasted to
UNDER THE HOOD OF FUTURES AND PROMISES IN SWIFT Under the hood of Futures and Promises in Swift. Asynchronous programming is arguably one of the most difficult parts of building modern apps. Whether it’s handling background tasks such as network requests, performing heavy operations in parallel across multiple threads, or executing code with a delay — asynchronous code canoften be hard
SWIFT BY SUNDELLWEEKLY ARTICLESBASICSPODCASTTIPSVIDEOSQ&A Thanks a lot to Matteo Manferdini for sponsoring Swift by Sundell last week to promote his SwiftUI guide “Architecting SwiftUI apps with MVC and MVVM”. The guide is completely free to download, and contains lots of practical tips and examples on how to PUBLISHED PROPERTIES IN SWIFT Conclusion. While Combine is a complex and powerful framework with a ton of different APIs and capabilities, the @Published property wrapper is one of its core aspects when it comes to UI development specifically — as it lets us easily set up reactive data bindings between our models and our UI. Combine might be limited to the latestversions
THE POWER OF KEY PATHS IN SWIFT The basics. Key paths essentially let us reference any instance property as a separate value. As such, they can be passed around, used in expressions, and enable a piece of code to get or set a property without actually knowing which exact property its working with. FORMATTING NUMBERS IN SWIFT Solving the decimal problem. At the most basic level, creating a textual representation of a given number simply involves initializing a String with it, which can either be done directly, or by using a string literal:. let a = String (42) // "42" let b = String (3.14) // "3.14" let c = " \(42), \(3.14) " // "42, 3.14". However, while that approach might work well for generating simpler CREATING CUSTOM SWIFTUI CONTAINER VIEWS Although SwiftUI ships with a quite large number of built-in container views, such as VStack, HStack and List, sometimes we might also want to define our own custom containers as well.. For example, let’s say that we’re working on an app that features a carousel-like component, which lets our users scroll through a horizontal list of items. That component is currently implemented like this: INTEGRATION TESTS IN SWIFT The integration of multiple units. Any code base can usually be separated into different parts — both by high-level features, such as Search, Login, Networking, and so on — and at a much lower level, by looking at individual classes and functions.A common way to test all those different parts is to do unit testing, and test each part (or unit) in isolation. BUILDING CUSTOM COMBINE PUBLISHERS IN SWIFT Building custom Combine publishers in Swift. Apple’s Combine framework provides a general-purpose abstraction for asynchronous programming, by enabling various values and events to be emitted, transformed and observed over time. Within the world of Combine, an object that emits such asynchronous values and events is called apublisher, and
REFLECTION IN SWIFT
Reflection is a common programming language feature that enables us to inspect, and work with, the members of a type — dynamically, at runtime. That may seem at odds with Swift’s heavy focus on compile-time validation — but this week, let’s take a look at when reflection can come in handy, and how it can let us make our code abit more dynamic.
OBSERVERS IN SWIFT
Observers in Swift - Part 1. observers. design patterns. Swift 5.0. Published on 15 Apr 2018. Often when building apps, we find ourselves in situations when we need to set up a one-to-many relationship between objects. It can be when multiple objects want to react to changes in the same state, or when a certain event needs to bebroadcasted to
UNDER THE HOOD OF FUTURES AND PROMISES IN SWIFT Under the hood of Futures and Promises in Swift. Asynchronous programming is arguably one of the most difficult parts of building modern apps. Whether it’s handling background tasks such as network requests, performing heavy operations in parallel across multiple threads, or executing code with a delay — asynchronous code canoften be hard
WORKING WITH FILES AND FOLDERS IN SWIFT URLs, locations, and data. Fundamentally, there are two Foundation types that are especially important when reading and writing files in Swift — URL and Data.Just like when performing network calls, URLs are used to point to various locations on disk, which we can then either read binary data from, or write new data into. FORMATTING NUMBERS IN SWIFT Solving the decimal problem. At the most basic level, creating a textual representation of a given number simply involves initializing a String with it, which can either be done directly, or by using a string literal:. let a = String (42) // "42" let b = String (3.14) // "3.14" let c = " \(42), \(3.14) " // "42, 3.14". However, while that approach might work well for generating simpler MAP, FLATMAP AND COMPACTMAP One way of transforming values in Swift is by mapping a collection into an array of new values, using a transform. The Swift standard library offers three main APIs for that kind of mapping — map, flatMap and compactMap. Let’s take a look at how they work.REFLECTION IN SWIFT
Reflection is a common programming language feature that enables us to inspect, and work with, the members of a type — dynamically, at runtime. That may seem at odds with Swift’s heavy focus on compile-time validation — but this week, let’s take a look at when reflection can come in handy, and how it can let us make our code abit more dynamic.
OBSERVERS IN SWIFT
Observers in Swift - Part 1. observers. design patterns. Swift 5.0. Published on 15 Apr 2018. Often when building apps, we find ourselves in situations when we need to set up a one-to-many relationship between objects. It can be when multiple objects want to react to changes in the same state, or when a certain event needs to bebroadcasted to
CONSTRUCTING URLS IN SWIFT Most modern apps require some form of networking - which means working with URLs in different shapes and forms. However, constructing URLs - especially dynamic ones based on user input - isn't always straight forward, and can lead to a wide range of bugs and problems if we'renot careful.
CUSTOM CONTAINER VIEW CONTROLLERS IN SWIFT Custom container view controllers in Swift. View controller containment has been an essential part of UIKit ever since the early days of the iPhone. With classes like UINavigationController and UITabBarController, container view controllers in many ways define how we interact with most apps on iOS and how their various screens arestructured
AVOIDING DEEPLY NESTED SWIFT CODE Avoiding deeply nested Swift code. Code style and structure are arguably two of the trickiest topics within programming in general. Not because they require any particular skills or vast experience building software, but because they’re so incredibly subjective in nature. What one person might consider the most readable and elegantly PATTERN MATCHING IN SWIFT Pattern matching in Swift. One really elegant aspect of Swift’s design is how it manages to hide much of its power and complexity behind much simpler programming constructs. Take something like a for loop, or a switch statement — on the surface, both work much the same way in Swift as they do in other languages — but dive a fewlevels
BUILDING A COMMAND LINE TOOL USING THE SWIFT PACKAGE Getting started. To start building a command line tool, make a new directory and initialize it using SPM: $ mkdir CommandLineTool $ cd CommandLineTool $ swift package init --type executable. The type executable above tells SPM that you want to build a command line tool,rather than a
SWIFT BY SUNDELLWEEKLY ARTICLESBASICSPODCASTTIPSVIDEOSQ&A With the start of WWDC21 just around the corner, I’d like to continue the tradition that I started in 2019, and share some of my biggest hopes and dreams for this year’s edition of the conference.. Note that these are really not predictions, nor are they based on any kind of insider information.It’s just me sharing some of my personal Swift-related WWDC dreams with you. PUBLISHED PROPERTIES IN SWIFT Conclusion. While Combine is a complex and powerful framework with a ton of different APIs and capabilities, the @Published property wrapper is one of its core aspects when it comes to UI development specifically — as it lets us easily set up reactive data bindings between our models and our UI.. Combine might be limited to the latest versions of Apple’s operating systems, but we could THE POWER OF KEY PATHS IN SWIFT The basics. Key paths essentially let us reference any instance property as a separate value. As such, they can be passed around, used in expressions, and enable a piece of code to get or set a property without actually knowing which exact property its working with. BUILDING CUSTOM COMBINE PUBLISHERS IN SWIFT Instabug: Whether it’s crashes, slow screen transitions, delayed network calls, or unresponsive UIs — Instabug automatically gives you all of the logs you need to fix bugs and issues, and to ship high-quality apps. Get started now. WORKING WITH FILES AND FOLDERS IN SWIFT URLs, locations, and data. Fundamentally, there are two Foundation types that are especially important when reading and writing files in Swift — URL and Data.Just like when performing network calls, URLs are used to point to various locations on disk, which we can then either read binary data from, or write new data into.OBSERVERS IN SWIFT
Often when building apps, we find ourselves in situations when we need to set up a one-to-many relationship between objects. In such situations, it's very common to want to add some way for certain objects to be observed. We'll start by taking a look at two such observation techniques this week, and then next week we'll continue with a couple of other ones.REFLECTION IN SWIFT
Reflection is a common programming language feature that enables us to inspect, and work with, the members of a type — dynamically, at runtime. That may seem at odds with Swift’s heavy focus on compile-time validation — but this week, let’s take a look at when reflection can come in handy, and how it can let us make our code abit more dynamic.
INTEGRATION TESTS IN SWIFT The integration of multiple units. Any code base can usually be separated into different parts — both by high-level features, such as Search, Login, Networking, and so on — and at a much lower level, by looking at individual classes and functions.A common way to test all those different parts is to do unit testing, and test each part (or unit) in isolation. FORMATTING NUMBERS IN SWIFT Solving the decimal problem. At the most basic level, creating a textual representation of a given number simply involves initializing a String with it, which can either be done directly, or by using a string literal:. let a = String (42) // "42" let b = String (3.14) // "3.14" let c = " \(42), \(3.14) " // "42, 3.14". However, while that approach might work well for generating simpler CREATING CUSTOM SWIFTUI CONTAINER VIEWS Although SwiftUI ships with a quite large number of built-in container views, such as VStack, HStack and List, sometimes we might also want to define our own custom containers as well.. For example, let’s say that we’re working on an app that features a carousel-like component, which lets our users scroll through a horizontal list of items. That component is currently implemented like this: SWIFT BY SUNDELLWEEKLY ARTICLESBASICSPODCASTTIPSVIDEOSQ&A With the start of WWDC21 just around the corner, I’d like to continue the tradition that I started in 2019, and share some of my biggest hopes and dreams for this year’s edition of the conference.. Note that these are really not predictions, nor are they based on any kind of insider information.It’s just me sharing some of my personal Swift-related WWDC dreams with you. PUBLISHED PROPERTIES IN SWIFT Conclusion. While Combine is a complex and powerful framework with a ton of different APIs and capabilities, the @Published property wrapper is one of its core aspects when it comes to UI development specifically — as it lets us easily set up reactive data bindings between our models and our UI.. Combine might be limited to the latest versions of Apple’s operating systems, but we could THE POWER OF KEY PATHS IN SWIFT The basics. Key paths essentially let us reference any instance property as a separate value. As such, they can be passed around, used in expressions, and enable a piece of code to get or set a property without actually knowing which exact property its working with. BUILDING CUSTOM COMBINE PUBLISHERS IN SWIFT Instabug: Whether it’s crashes, slow screen transitions, delayed network calls, or unresponsive UIs — Instabug automatically gives you all of the logs you need to fix bugs and issues, and to ship high-quality apps. Get started now. WORKING WITH FILES AND FOLDERS IN SWIFT URLs, locations, and data. Fundamentally, there are two Foundation types that are especially important when reading and writing files in Swift — URL and Data.Just like when performing network calls, URLs are used to point to various locations on disk, which we can then either read binary data from, or write new data into.OBSERVERS IN SWIFT
Often when building apps, we find ourselves in situations when we need to set up a one-to-many relationship between objects. In such situations, it's very common to want to add some way for certain objects to be observed. We'll start by taking a look at two such observation techniques this week, and then next week we'll continue with a couple of other ones.REFLECTION IN SWIFT
Reflection is a common programming language feature that enables us to inspect, and work with, the members of a type — dynamically, at runtime. That may seem at odds with Swift’s heavy focus on compile-time validation — but this week, let’s take a look at when reflection can come in handy, and how it can let us make our code abit more dynamic.
INTEGRATION TESTS IN SWIFT The integration of multiple units. Any code base can usually be separated into different parts — both by high-level features, such as Search, Login, Networking, and so on — and at a much lower level, by looking at individual classes and functions.A common way to test all those different parts is to do unit testing, and test each part (or unit) in isolation. FORMATTING NUMBERS IN SWIFT Solving the decimal problem. At the most basic level, creating a textual representation of a given number simply involves initializing a String with it, which can either be done directly, or by using a string literal:. let a = String (42) // "42" let b = String (3.14) // "3.14" let c = " \(42), \(3.14) " // "42, 3.14". However, while that approach might work well for generating simpler CREATING CUSTOM SWIFTUI CONTAINER VIEWS Although SwiftUI ships with a quite large number of built-in container views, such as VStack, HStack and List, sometimes we might also want to define our own custom containers as well.. For example, let’s say that we’re working on an app that features a carousel-like component, which lets our users scroll through a horizontal list of items. That component is currently implemented like this:REFLECTION IN SWIFT
Reflection is a common programming language feature that enables us to inspect, and work with, the members of a type — dynamically, at runtime. That may seem at odds with Swift’s heavy focus on compile-time validation — but this week, let’s take a look at when reflection can come in handy, and how it can let us make our code abit more dynamic.
MAP, FLATMAP AND COMPACTMAP One way of transforming values in Swift is by mapping a collection into an array of new values, using a transform. The Swift standard library offers three main APIs for that kind of mapping — map, flatMap and compactMap. Let’s take a look at how they work. CONSTRUCTING URLS IN SWIFT Most modern apps require some form of networking - which means working with URLs in different shapes and forms. However, constructing URLs - especially dynamic ones based on user input - isn't always straight forward, and can lead to a wide range of bugs and problems if we'renot careful.
FORMATTING NUMBERS IN SWIFT Solving the decimal problem. At the most basic level, creating a textual representation of a given number simply involves initializing a String with it, which can either be done directly, or by using a string literal:. let a = String (42) // "42" let b = String (3.14) // "3.14" let c = " \(42), \(3.14) " // "42, 3.14". However, while that approach might work well for generating simplerOBSERVERS IN SWIFT
Often when building apps, we find ourselves in situations when we need to set up a one-to-many relationship between objects. In such situations, it's very common to want to add some way for certain objects to be observed. We'll start by taking a look at two such observation techniques this week, and then next week we'll continue with a couple of other ones.PREDICATES IN SWIFT
Predicates can enable us to filter various collections in ways that are incredibly flexible. Let’s take a look at how we could constructpowerful, type
AVOIDING DEEPLY NESTED SWIFT CODE Essential Developer: If you’re a mid/senior iOS developer who’s looking to improve both your skills and your salary level, then join this 100% free online crash course, starting on May 17th. Through a series of lectures and coding sessions you’ll learn how to become a BUILDING A COMMAND LINE TOOL USING THE SWIFT PACKAGE This week, I’d like to provide a step-by-step tutorial for the setup that I use to build command line tools using the Swift Package Manager.. I personally really like the Swift Package Manager (which I will from now on refer to as ‘SPM’ to save me some typing 😅) and how easy it is to use once you get up and running. PATTERN MATCHING IN SWIFT One really elegant aspect of Swift’s design is how it manages to hide much of its power behind much simpler programming constructs. Pattern matching is one source of that power, especially considering how it’s integrated into many different aspects of the language. MANAGING OBJECTS USING LOCKS AND KEYS IN SWIFT One of the most important roles of any software architecture is to make the relationships between the various objects and values within an application as clear as possible. This week, let's take a look at how we can do that by using the type system to set up locks and keys to get a stronger, compile-time guarantee that the intended flow of our app will remain intact at runtime. SWIFT BY SUNDELLWEEKLY ARTICLESBASICSPODCASTTIPSVIDEOSQ&A Thanks a lot to Matteo Manferdini for sponsoring Swift by Sundell last week to promote his SwiftUI guide “Architecting SwiftUI apps with MVC and MVVM”. The guide is completely free to download, and contains lots of practical tips and examples on how to PUBLISHED PROPERTIES IN SWIFT Conclusion. While Combine is a complex and powerful framework with a ton of different APIs and capabilities, the @Published property wrapper is one of its core aspects when it comes to UI development specifically — as it lets us easily set up reactive data bindings between our models and our UI.. Combine might be limited to the latest versions of Apple’s operating systems, but we could WORKING WITH FILES AND FOLDERS IN SWIFT URLs, locations, and data. Fundamentally, there are two Foundation types that are especially important when reading and writing files in Swift — URL and Data.Just like when performing network calls, URLs are used to point to various locations on disk, which we can then either read binary data from, or write new data into. COMBINE | SWIFT BY SUNDELL combine. reactive programming. Swift 5.2. Published on 16 Apr 2020. Introduced during WWDC 2019, Apple’s Combine framework lets us model all sorts of asynchronous events and operations as “values over time”. While that’s a phrase that’s commonly used within the reactive programming world, as a concept and way of constructinglogic, it
MAP, FLATMAP AND COMPACTMAP One way of transforming values in Swift is by mapping a collection into an array of new values, using a transform. The Swift standard library offers three main APIs for that kind of mapping — map, flatMap and compactMap. Let’s take a look at how they work. FORMATTING NUMBERS IN SWIFT Solving the decimal problem. At the most basic level, creating a textual representation of a given number simply involves initializing a String with it, which can either be done directly, or by using a string literal:. let a = String (42) // "42" let b = String (3.14) // "3.14" let c = " \(42), \(3.14) " // "42, 3.14". However, while that approach might work well for generating simpler THE POWER OF KEY PATHS IN SWIFT The basics. Key paths essentially let us reference any instance property as a separate value. As such, they can be passed around, used in expressions, and enable a piece of code to get or set a property without actually knowing which exact property its working with. CONSTRUCTING URLS IN SWIFT Most modern apps require some form of networking - which means working with URLs in different shapes and forms. However, constructing URLs - especially dynamic ones based on user input - isn't always straight forward, and can lead to a wide range of bugs and problems if we'renot careful.
BUILDING CUSTOM COMBINE PUBLISHERS IN SWIFT Building custom Combine publishers in Swift. Apple’s Combine framework provides a general-purpose abstraction for asynchronous programming, by enabling various values and events to be emitted, transformed and observed over time. Within the world of Combine, an object that emits such asynchronous values and events is called apublisher, and
CONTROLLING THE TIMING OF A COMBINE PIPELINE Controlling the timing of a Combine pipeline. Often when writing Combine-powered data pipelines, we want those pipelines to emit values as quickly as possible, as soon as each operation finishes. However, sometimes we might also want to introduce certain delays in order to prevent unnecessary work from being performed, or to be able to retrya
SWIFT BY SUNDELLWEEKLY ARTICLESBASICSPODCASTTIPSVIDEOSQ&A Thanks a lot to Matteo Manferdini for sponsoring Swift by Sundell last week to promote his SwiftUI guide “Architecting SwiftUI apps with MVC and MVVM”. The guide is completely free to download, and contains lots of practical tips and examples on how to PUBLISHED PROPERTIES IN SWIFT Conclusion. While Combine is a complex and powerful framework with a ton of different APIs and capabilities, the @Published property wrapper is one of its core aspects when it comes to UI development specifically — as it lets us easily set up reactive data bindings between our models and our UI.. Combine might be limited to the latest versions of Apple’s operating systems, but we could WORKING WITH FILES AND FOLDERS IN SWIFT URLs, locations, and data. Fundamentally, there are two Foundation types that are especially important when reading and writing files in Swift — URL and Data.Just like when performing network calls, URLs are used to point to various locations on disk, which we can then either read binary data from, or write new data into. COMBINE | SWIFT BY SUNDELL combine. reactive programming. Swift 5.2. Published on 16 Apr 2020. Introduced during WWDC 2019, Apple’s Combine framework lets us model all sorts of asynchronous events and operations as “values over time”. While that’s a phrase that’s commonly used within the reactive programming world, as a concept and way of constructinglogic, it
MAP, FLATMAP AND COMPACTMAP One way of transforming values in Swift is by mapping a collection into an array of new values, using a transform. The Swift standard library offers three main APIs for that kind of mapping — map, flatMap and compactMap. Let’s take a look at how they work. FORMATTING NUMBERS IN SWIFT Solving the decimal problem. At the most basic level, creating a textual representation of a given number simply involves initializing a String with it, which can either be done directly, or by using a string literal:. let a = String (42) // "42" let b = String (3.14) // "3.14" let c = " \(42), \(3.14) " // "42, 3.14". However, while that approach might work well for generating simpler THE POWER OF KEY PATHS IN SWIFT The basics. Key paths essentially let us reference any instance property as a separate value. As such, they can be passed around, used in expressions, and enable a piece of code to get or set a property without actually knowing which exact property its working with. CONSTRUCTING URLS IN SWIFT Most modern apps require some form of networking - which means working with URLs in different shapes and forms. However, constructing URLs - especially dynamic ones based on user input - isn't always straight forward, and can lead to a wide range of bugs and problems if we'renot careful.
BUILDING CUSTOM COMBINE PUBLISHERS IN SWIFT Building custom Combine publishers in Swift. Apple’s Combine framework provides a general-purpose abstraction for asynchronous programming, by enabling various values and events to be emitted, transformed and observed over time. Within the world of Combine, an object that emits such asynchronous values and events is called apublisher, and
CONTROLLING THE TIMING OF A COMBINE PIPELINE Controlling the timing of a Combine pipeline. Often when writing Combine-powered data pipelines, we want those pipelines to emit values as quickly as possible, as soon as each operation finishes. However, sometimes we might also want to introduce certain delays in order to prevent unnecessary work from being performed, or to be able to retrya
SWIFT BY SUNDELL
Thanks a lot to Matteo Manferdini for sponsoring Swift by Sundell last week to promote his SwiftUI guide “Architecting SwiftUI apps with MVC and MVVM”. The guide is completely free to download, and contains lots of practical tips and examples on how to COMBINE | SWIFT BY SUNDELL combine. reactive programming. Swift 5.2. Published on 16 Apr 2020. Introduced during WWDC 2019, Apple’s Combine framework lets us model all sorts of asynchronous events and operations as “values over time”. While that’s a phrase that’s commonly used within the reactive programming world, as a concept and way of constructinglogic, it
PREDICATES IN SWIFT
In Swift, operator implementations are just normal functions that take their operands as arguments (in this case a left-hand side one, and a right-hand side one). Using the above, we can now create matching predicates like this: let uncompletedItems = list. items (matching: \. isCompleted == false) That’s pretty cool! CONSTRUCTING URLS IN SWIFT Most modern apps require some form of networking - which means working with URLs in different shapes and forms. However, constructing URLs - especially dynamic ones based on user input - isn't always straight forward, and can lead to a wide range of bugs and problems if we'renot careful.
UNIT TESTING COMBINE-BASED SWIFT CODE Unit testing Combine-based Swift code. Testing asynchronous code is often particularly tricky, and code written using Apple’s Combine framework is no exception. Since each XCTest-based unit test executes in a purely synchronous fashion, we have to find ways to tell the test runner to await the output of the various asynchronous calls that we BUILDING CUSTOM COMBINE PUBLISHERS IN SWIFT Building custom Combine publishers in Swift. Apple’s Combine framework provides a general-purpose abstraction for asynchronous programming, by enabling various values and events to be emitted, transformed and observed over time. Within the world of Combine, an object that emits such asynchronous values and events is called apublisher, and
OBSERVERS IN SWIFT
Observers in Swift - Part 1. observers. design patterns. Swift 5.0. Published on 15 Apr 2018. Often when building apps, we find ourselves in situations when we need to set up a one-to-many relationship between objects. It can be when multiple objects want to react to changes in the same state, or when a certain event needs to bebroadcasted to
REFLECTION IN SWIFT
Reflection is a common programming language feature that enables us to inspect, and work with, the members of a type — dynamically, at runtime. That may seem at odds with Swift’s heavy focus on compile-time validation — but this week, let’s take a look at when reflection can come in handy, and how it can let us make our code abit more dynamic.
CACHING IN SWIFT
Let’s take a look at how caching can be an incredibly powerful tool in various situations, how to build an efficient and elegant caching API in Swift, and how strategically caching various values and objects can have a big impact on the overall performance of an app. CHILD VIEW CONTROLLERS Just like how a UIView can be added to another UIView to form a hierarchy, a view controller can become the child of another view controller. That enables us to compose our UI from multiple building blocks, which can lead to smaller view controller implementations that are easier to reuse. SWIFT BY SUNDELLWEEKLY ARTICLESBASICSPODCASTTIPSVIDEOSQ&A Thanks a lot to Matteo Manferdini for sponsoring Swift by Sundell last week to promote his SwiftUI guide “Architecting SwiftUI apps with MVC and MVVM”. The guide is completely free to download, and contains lots of practical tips and examples on how to WORKING WITH FILES AND FOLDERS IN SWIFT URLs, locations, and data. Fundamentally, there are two Foundation types that are especially important when reading and writing files in Swift — URL and Data.Just like when performing network calls, URLs are used to point to various locations on disk, which we can then either read binary data from, or write new data into. PUBLISHED PROPERTIES IN SWIFT Conclusion. While Combine is a complex and powerful framework with a ton of different APIs and capabilities, the @Published property wrapper is one of its core aspects when it comes to UI development specifically — as it lets us easily set up reactive data bindings between our models and our UI. Combine might be limited to the latestversions
COMBINE | SWIFT BY SUNDELL combine. reactive programming. Swift 5.2. Published on 16 Apr 2020. Introduced during WWDC 2019, Apple’s Combine framework lets us model all sorts of asynchronous events and operations as “values over time”. While that’s a phrase that’s commonly used within the reactive programming world, as a concept and way of constructinglogic, it
FORMATTING NUMBERS IN SWIFT Solving the decimal problem. At the most basic level, creating a textual representation of a given number simply involves initializing a String with it, which can either be done directly, or by using a string literal:. let a = String (42) // "42" let b = String (3.14) // "3.14" let c = " \(42), \(3.14) " // "42, 3.14". However, while that approach might work well for generating simpler MAP, FLATMAP AND COMPACTMAP One way of transforming values in Swift is by mapping a collection into an array of new values, using a transform. The Swift standard library offers three main APIs for that kind of mapping — map, flatMap and compactMap. Let’s take a look at how they work. THE POWER OF KEY PATHS IN SWIFT The basics. Key paths essentially let us reference any instance property as a separate value. As such, they can be passed around, used in expressions, and enable a piece of code to get or set a property without actually knowing which exact property its working with. CONSTRUCTING URLS IN SWIFT Most modern apps require some form of networking - which means working with URLs in different shapes and forms. However, constructing URLs - especially dynamic ones based on user input - isn't always straight forward, and can lead to a wide range of bugs and problems if we'renot careful.
BUILDING CUSTOM COMBINE PUBLISHERS IN SWIFT Building custom Combine publishers in Swift. Apple’s Combine framework provides a general-purpose abstraction for asynchronous programming, by enabling various values and events to be emitted, transformed and observed over time. Within the world of Combine, an object that emits such asynchronous values and events is called apublisher, and
CONTROLLING THE TIMING OF A COMBINE PIPELINE Controlling the timing of a Combine pipeline. Often when writing Combine-powered data pipelines, we want those pipelines to emit values as quickly as possible, as soon as each operation finishes. However, sometimes we might also want to introduce certain delays in order to prevent unnecessary work from being performed, or to be able to retrya
SWIFT BY SUNDELLWEEKLY ARTICLESBASICSPODCASTTIPSVIDEOSQ&A Thanks a lot to Matteo Manferdini for sponsoring Swift by Sundell last week to promote his SwiftUI guide “Architecting SwiftUI apps with MVC and MVVM”. The guide is completely free to download, and contains lots of practical tips and examples on how to WORKING WITH FILES AND FOLDERS IN SWIFT URLs, locations, and data. Fundamentally, there are two Foundation types that are especially important when reading and writing files in Swift — URL and Data.Just like when performing network calls, URLs are used to point to various locations on disk, which we can then either read binary data from, or write new data into. PUBLISHED PROPERTIES IN SWIFT Conclusion. While Combine is a complex and powerful framework with a ton of different APIs and capabilities, the @Published property wrapper is one of its core aspects when it comes to UI development specifically — as it lets us easily set up reactive data bindings between our models and our UI. Combine might be limited to the latestversions
COMBINE | SWIFT BY SUNDELL combine. reactive programming. Swift 5.2. Published on 16 Apr 2020. Introduced during WWDC 2019, Apple’s Combine framework lets us model all sorts of asynchronous events and operations as “values over time”. While that’s a phrase that’s commonly used within the reactive programming world, as a concept and way of constructinglogic, it
FORMATTING NUMBERS IN SWIFT Solving the decimal problem. At the most basic level, creating a textual representation of a given number simply involves initializing a String with it, which can either be done directly, or by using a string literal:. let a = String (42) // "42" let b = String (3.14) // "3.14" let c = " \(42), \(3.14) " // "42, 3.14". However, while that approach might work well for generating simpler MAP, FLATMAP AND COMPACTMAP One way of transforming values in Swift is by mapping a collection into an array of new values, using a transform. The Swift standard library offers three main APIs for that kind of mapping — map, flatMap and compactMap. Let’s take a look at how they work. THE POWER OF KEY PATHS IN SWIFT The basics. Key paths essentially let us reference any instance property as a separate value. As such, they can be passed around, used in expressions, and enable a piece of code to get or set a property without actually knowing which exact property its working with. CONSTRUCTING URLS IN SWIFT Most modern apps require some form of networking - which means working with URLs in different shapes and forms. However, constructing URLs - especially dynamic ones based on user input - isn't always straight forward, and can lead to a wide range of bugs and problems if we'renot careful.
BUILDING CUSTOM COMBINE PUBLISHERS IN SWIFT Building custom Combine publishers in Swift. Apple’s Combine framework provides a general-purpose abstraction for asynchronous programming, by enabling various values and events to be emitted, transformed and observed over time. Within the world of Combine, an object that emits such asynchronous values and events is called apublisher, and
CONTROLLING THE TIMING OF A COMBINE PIPELINE Controlling the timing of a Combine pipeline. Often when writing Combine-powered data pipelines, we want those pipelines to emit values as quickly as possible, as soon as each operation finishes. However, sometimes we might also want to introduce certain delays in order to prevent unnecessary work from being performed, or to be able to retrya
SWIFT BY SUNDELL
Thanks a lot to Matteo Manferdini for sponsoring Swift by Sundell last week to promote his SwiftUI guide “Architecting SwiftUI apps with MVC and MVVM”. The guide is completely free to download, and contains lots of practical tips and examples on how to COMBINE | SWIFT BY SUNDELL combine. reactive programming. Swift 5.2. Published on 16 Apr 2020. Introduced during WWDC 2019, Apple’s Combine framework lets us model all sorts of asynchronous events and operations as “values over time”. While that’s a phrase that’s commonly used within the reactive programming world, as a concept and way of constructinglogic, it
CONSTRUCTING URLS IN SWIFT Most modern apps require some form of networking - which means working with URLs in different shapes and forms. However, constructing URLs - especially dynamic ones based on user input - isn't always straight forward, and can lead to a wide range of bugs and problems if we'renot careful.
PREDICATES IN SWIFT
In Swift, operator implementations are just normal functions that take their operands as arguments (in this case a left-hand side one, and a right-hand side one). Using the above, we can now create matching predicates like this: let uncompletedItems = list. items (matching: \. isCompleted == false) That’s pretty cool! UNIT TESTING COMBINE-BASED SWIFT CODE Unit testing Combine-based Swift code. Testing asynchronous code is often particularly tricky, and code written using Apple’s Combine framework is no exception. Since each XCTest-based unit test executes in a purely synchronous fashion, we have to find ways to tell the test runner to await the output of the various asynchronous calls that we BUILDING CUSTOM COMBINE PUBLISHERS IN SWIFT Building custom Combine publishers in Swift. Apple’s Combine framework provides a general-purpose abstraction for asynchronous programming, by enabling various values and events to be emitted, transformed and observed over time. Within the world of Combine, an object that emits such asynchronous values and events is called apublisher, and
OBSERVERS IN SWIFT
Observers in Swift - Part 1. observers. design patterns. Swift 5.0. Published on 15 Apr 2018. Often when building apps, we find ourselves in situations when we need to set up a one-to-many relationship between objects. It can be when multiple objects want to react to changes in the same state, or when a certain event needs to bebroadcasted to
REFLECTION IN SWIFT
Reflection is a common programming language feature that enables us to inspect, and work with, the members of a type — dynamically, at runtime. That may seem at odds with Swift’s heavy focus on compile-time validation — but this week, let’s take a look at when reflection can come in handy, and how it can let us make our code abit more dynamic.
CHILD VIEW CONTROLLERS To add a view controller as a child, we use the following three API calls: let parent = UIViewController () let child = UIViewController () // First, add the view of the child to the view of the parent parent. view. addSubview (child. view ) // Then, add the child to the parent parent. addChild (child) // Finally, notify the child that itwas
CACHING IN SWIFT
Let’s take a look at how caching can be an incredibly powerful tool in various situations, how to build an efficient and elegant caching API in Swift, and how strategically caching various values and objects can have a big impact on the overall performance of an app. SWIFT BY SUNDELLWEEKLY ARTICLESBASICSPODCASTTIPSVIDEOSQ&A Swift’s implementation of enums is, without a doubt, one of the most beloved and powerful features that the language has to offer. The fact that Swift enums go way beyond simple enumerations of integer-based constants, and support things like associated values and sophisticated pattern matching, makes them a great candidate for solving many WORKING WITH FILES AND FOLDERS IN SWIFT URLs, locations, and data. Fundamentally, there are two Foundation types that are especially important when reading and writing files in Swift — URL and Data.Just like when performing network calls, URLs are used to point to various locations on disk, which we can then either read binary data from, or write new data into. MAP, FLATMAP AND COMPACTMAP One way of transforming values in Swift is by mapping a collection into an array of new values, using a transform. The Swift standard library offers three main APIs for that kind of mapping — map, flatMap and compactMap. Let’s take a look at how they work.REFLECTION IN SWIFT
Reflection is a common programming language feature that enables us to inspect, and work with, the members of a type — dynamically, at runtime. That may seem at odds with Swift’s heavy focus on compile-time validation — but this week, let’s take a look at when reflection can come in handy, and how it can let us make our code abit more dynamic.
PUBLISHED PROPERTIES IN SWIFT Conclusion. While Combine is a complex and powerful framework with a ton of different APIs and capabilities, the @Published property wrapper is one of its core aspects when it comes to UI development specifically — as it lets us easily set up reactive data bindings between our models and our UI. Combine might be limited to the latestversions
BUILDING CUSTOM COMBINE PUBLISHERS IN SWIFT Building custom Combine publishers in Swift. Apple’s Combine framework provides a general-purpose abstraction for asynchronous programming, by enabling various values and events to be emitted, transformed and observed over time. Within the world of Combine, an object that emits such asynchronous values and events is called apublisher, and
CREATING CUSTOM SWIFTUI CONTAINER VIEWS Although SwiftUI ships with a quite large number of built-in container views, such as VStack, HStack and List, sometimes we might also want to define our own custom containers as well.. For example, let’s say that we’re working on an app that features a carousel-like component, which lets our users scroll through a horizontal list of items. That component is currently implemented like this:OBSERVERS IN SWIFT
Observers in Swift - Part 1. observers. design patterns. Swift 5.0. Published on 15 Apr 2018. Often when building apps, we find ourselves in situations when we need to set up a one-to-many relationship between objects. It can be when multiple objects want to react to changes in the same state, or when a certain event needs to bebroadcasted to
INTEGRATION TESTS IN SWIFT The integration of multiple units. Any code base can usually be separated into different parts — both by high-level features, such as Search, Login, Networking, and so on — and at a much lower level, by looking at individual classes and functions.A common way to test all those different parts is to do unit testing, and test each part (or unit) in isolation. AVOIDING DEEPLY NESTED SWIFT CODE Avoiding deeply nested Swift code. Code style and structure are arguably two of the trickiest topics within programming in general. Not because they require any particular skills or vast experience building software, but because they’re so incredibly subjective in nature. What one person might consider the most readable and elegantly SWIFT BY SUNDELLWEEKLY ARTICLESBASICSPODCASTTIPSVIDEOSQ&A Swift’s implementation of enums is, without a doubt, one of the most beloved and powerful features that the language has to offer. The fact that Swift enums go way beyond simple enumerations of integer-based constants, and support things like associated values and sophisticated pattern matching, makes them a great candidate for solving many WORKING WITH FILES AND FOLDERS IN SWIFT URLs, locations, and data. Fundamentally, there are two Foundation types that are especially important when reading and writing files in Swift — URL and Data.Just like when performing network calls, URLs are used to point to various locations on disk, which we can then either read binary data from, or write new data into. MAP, FLATMAP AND COMPACTMAP One way of transforming values in Swift is by mapping a collection into an array of new values, using a transform. The Swift standard library offers three main APIs for that kind of mapping — map, flatMap and compactMap. Let’s take a look at how they work.REFLECTION IN SWIFT
Reflection is a common programming language feature that enables us to inspect, and work with, the members of a type — dynamically, at runtime. That may seem at odds with Swift’s heavy focus on compile-time validation — but this week, let’s take a look at when reflection can come in handy, and how it can let us make our code abit more dynamic.
PUBLISHED PROPERTIES IN SWIFT Conclusion. While Combine is a complex and powerful framework with a ton of different APIs and capabilities, the @Published property wrapper is one of its core aspects when it comes to UI development specifically — as it lets us easily set up reactive data bindings between our models and our UI. Combine might be limited to the latestversions
BUILDING CUSTOM COMBINE PUBLISHERS IN SWIFT Building custom Combine publishers in Swift. Apple’s Combine framework provides a general-purpose abstraction for asynchronous programming, by enabling various values and events to be emitted, transformed and observed over time. Within the world of Combine, an object that emits such asynchronous values and events is called apublisher, and
CREATING CUSTOM SWIFTUI CONTAINER VIEWS Although SwiftUI ships with a quite large number of built-in container views, such as VStack, HStack and List, sometimes we might also want to define our own custom containers as well.. For example, let’s say that we’re working on an app that features a carousel-like component, which lets our users scroll through a horizontal list of items. That component is currently implemented like this:OBSERVERS IN SWIFT
Observers in Swift - Part 1. observers. design patterns. Swift 5.0. Published on 15 Apr 2018. Often when building apps, we find ourselves in situations when we need to set up a one-to-many relationship between objects. It can be when multiple objects want to react to changes in the same state, or when a certain event needs to bebroadcasted to
INTEGRATION TESTS IN SWIFT The integration of multiple units. Any code base can usually be separated into different parts — both by high-level features, such as Search, Login, Networking, and so on — and at a much lower level, by looking at individual classes and functions.A common way to test all those different parts is to do unit testing, and test each part (or unit) in isolation. AVOIDING DEEPLY NESTED SWIFT CODE Avoiding deeply nested Swift code. Code style and structure are arguably two of the trickiest topics within programming in general. Not because they require any particular skills or vast experience building software, but because they’re so incredibly subjective in nature. What one person might consider the most readable and elegantly COMBINE | SWIFT BY SUNDELL combine. reactive programming. Swift 5.2. Published on 16 Apr 2020. Introduced during WWDC 2019, Apple’s Combine framework lets us model all sorts of asynchronous events and operations as “values over time”. While that’s a phrase that’s commonly used within the reactive programming world, as a concept and way of constructinglogic, it
OBSERVERS IN SWIFT
Observers in Swift - Part 1. observers. design patterns. Swift 5.0. Published on 15 Apr 2018. Often when building apps, we find ourselves in situations when we need to set up a one-to-many relationship between objects. It can be when multiple objects want to react to changes in the same state, or when a certain event needs to bebroadcasted to
SWIFT CLIP: KEY PATHS AND FUNCTIONS Let’s take a look at how Swift’s key paths work, and how they relate to functions — both in terms of what comes built into the language itself, and what kind of utilities that we can write ourselves to form some really nice convenience APIs. FORMATTING NUMBERS IN SWIFT Solving the decimal problem. At the most basic level, creating a textual representation of a given number simply involves initializing a String with it, which can either be done directly, or by using a string literal:. let a = String (42) // "42" let b = String (3.14) // "3.14" let c = " \(42), \(3.14) " // "42, 3.14". However, while that approach might work well for generating simpler INTEGRATION TESTS IN SWIFT The integration of multiple units. Any code base can usually be separated into different parts — both by high-level features, such as Search, Login, Networking, and so on — and at a much lower level, by looking at individual classes and functions.A common way to test all those different parts is to do unit testing, and test each part (or unit) in isolation.PREDICATES IN SWIFT
In Swift, operator implementations are just normal functions that take their operands as arguments (in this case a left-hand side one, and a right-hand side one). Using the above, we can now create matching predicates like this: let uncompletedItems = list. items (matching: \. isCompleted == false) That’s pretty cool! CONSTRUCTING URLS IN SWIFT Most modern apps require some form of networking - which means working with URLs in different shapes and forms. However, constructing URLs - especially dynamic ones based on user input - isn't always straight forward, and can lead to a wide range of bugs and problems if we'renot careful.
THE POWER OF KEY PATHS IN SWIFT The basics. Key paths essentially let us reference any instance property as a separate value. As such, they can be passed around, used in expressions, and enable a piece of code to get or set a property without actually knowing which exact property its working with. GRAND CENTRAL DISPATCH Grand Central Dispatch. In Swift we have a few different options available to us when it comes to asynchronous programming — code that doesn’t immediately execute as part of our program’s main control flow, but rather is dispatched onto a different queue of execution. Grand Central Dispatch (or GCD for short) is one suchoption — and is
BINDABLE VALUES IN SWIFT Arguably one of the most challenging aspects of building apps for most platforms is making sure that the UI we present to the user always remains in sync with our underlying data models, and many techniques have been invented in order to address this problem. This week, let’s take a look at one such technique, that involves binding our model values to our UI. SWIFT BY SUNDELLWEEKLY ARTICLESBASICSPODCASTTIPSVIDEOSQ&A Swift’s implementation of enums is, without a doubt, one of the most beloved and powerful features that the language has to offer. The fact that Swift enums go way beyond simple enumerations of integer-based constants, and support things like associated values and sophisticated pattern matching, makes them a great candidate for solving many WORKING WITH FILES AND FOLDERS IN SWIFT URLs, locations, and data. Fundamentally, there are two Foundation types that are especially important when reading and writing files in Swift — URL and Data.Just like when performing network calls, URLs are used to point to various locations on disk, which we can then either read binary data from, or write new data into. MAP, FLATMAP AND COMPACTMAP One way of transforming values in Swift is by mapping a collection into an array of new values, using a transform. The Swift standard library offers three main APIs for that kind of mapping — map, flatMap and compactMap. Let’s take a look at how they work.REFLECTION IN SWIFT
Reflection is a common programming language feature that enables us to inspect, and work with, the members of a type — dynamically, at runtime. That may seem at odds with Swift’s heavy focus on compile-time validation — but this week, let’s take a look at when reflection can come in handy, and how it can let us make our code abit more dynamic.
PUBLISHED PROPERTIES IN SWIFT Conclusion. While Combine is a complex and powerful framework with a ton of different APIs and capabilities, the @Published property wrapper is one of its core aspects when it comes to UI development specifically — as it lets us easily set up reactive data bindings between our models and our UI. Combine might be limited to the latestversions
BUILDING CUSTOM COMBINE PUBLISHERS IN SWIFT Building custom Combine publishers in Swift. Apple’s Combine framework provides a general-purpose abstraction for asynchronous programming, by enabling various values and events to be emitted, transformed and observed over time. Within the world of Combine, an object that emits such asynchronous values and events is called apublisher, and
CREATING CUSTOM SWIFTUI CONTAINER VIEWS Although SwiftUI ships with a quite large number of built-in container views, such as VStack, HStack and List, sometimes we might also want to define our own custom containers as well.. For example, let’s say that we’re working on an app that features a carousel-like component, which lets our users scroll through a horizontal list of items. That component is currently implemented like this:OBSERVERS IN SWIFT
Observers in Swift - Part 1. observers. design patterns. Swift 5.0. Published on 15 Apr 2018. Often when building apps, we find ourselves in situations when we need to set up a one-to-many relationship between objects. It can be when multiple objects want to react to changes in the same state, or when a certain event needs to bebroadcasted to
INTEGRATION TESTS IN SWIFT The integration of multiple units. Any code base can usually be separated into different parts — both by high-level features, such as Search, Login, Networking, and so on — and at a much lower level, by looking at individual classes and functions.A common way to test all those different parts is to do unit testing, and test each part (or unit) in isolation. AVOIDING DEEPLY NESTED SWIFT CODE Avoiding deeply nested Swift code. Code style and structure are arguably two of the trickiest topics within programming in general. Not because they require any particular skills or vast experience building software, but because they’re so incredibly subjective in nature. What one person might consider the most readable and elegantly SWIFT BY SUNDELLWEEKLY ARTICLESBASICSPODCASTTIPSVIDEOSQ&A Swift’s implementation of enums is, without a doubt, one of the most beloved and powerful features that the language has to offer. The fact that Swift enums go way beyond simple enumerations of integer-based constants, and support things like associated values and sophisticated pattern matching, makes them a great candidate for solving many WORKING WITH FILES AND FOLDERS IN SWIFT URLs, locations, and data. Fundamentally, there are two Foundation types that are especially important when reading and writing files in Swift — URL and Data.Just like when performing network calls, URLs are used to point to various locations on disk, which we can then either read binary data from, or write new data into. MAP, FLATMAP AND COMPACTMAP One way of transforming values in Swift is by mapping a collection into an array of new values, using a transform. The Swift standard library offers three main APIs for that kind of mapping — map, flatMap and compactMap. Let’s take a look at how they work.REFLECTION IN SWIFT
Reflection is a common programming language feature that enables us to inspect, and work with, the members of a type — dynamically, at runtime. That may seem at odds with Swift’s heavy focus on compile-time validation — but this week, let’s take a look at when reflection can come in handy, and how it can let us make our code abit more dynamic.
PUBLISHED PROPERTIES IN SWIFT Conclusion. While Combine is a complex and powerful framework with a ton of different APIs and capabilities, the @Published property wrapper is one of its core aspects when it comes to UI development specifically — as it lets us easily set up reactive data bindings between our models and our UI. Combine might be limited to the latestversions
BUILDING CUSTOM COMBINE PUBLISHERS IN SWIFT Building custom Combine publishers in Swift. Apple’s Combine framework provides a general-purpose abstraction for asynchronous programming, by enabling various values and events to be emitted, transformed and observed over time. Within the world of Combine, an object that emits such asynchronous values and events is called apublisher, and
CREATING CUSTOM SWIFTUI CONTAINER VIEWS Although SwiftUI ships with a quite large number of built-in container views, such as VStack, HStack and List, sometimes we might also want to define our own custom containers as well.. For example, let’s say that we’re working on an app that features a carousel-like component, which lets our users scroll through a horizontal list of items. That component is currently implemented like this:OBSERVERS IN SWIFT
Observers in Swift - Part 1. observers. design patterns. Swift 5.0. Published on 15 Apr 2018. Often when building apps, we find ourselves in situations when we need to set up a one-to-many relationship between objects. It can be when multiple objects want to react to changes in the same state, or when a certain event needs to bebroadcasted to
INTEGRATION TESTS IN SWIFT The integration of multiple units. Any code base can usually be separated into different parts — both by high-level features, such as Search, Login, Networking, and so on — and at a much lower level, by looking at individual classes and functions.A common way to test all those different parts is to do unit testing, and test each part (or unit) in isolation. AVOIDING DEEPLY NESTED SWIFT CODE Avoiding deeply nested Swift code. Code style and structure are arguably two of the trickiest topics within programming in general. Not because they require any particular skills or vast experience building software, but because they’re so incredibly subjective in nature. What one person might consider the most readable and elegantly COMBINE | SWIFT BY SUNDELL combine. reactive programming. Swift 5.2. Published on 16 Apr 2020. Introduced during WWDC 2019, Apple’s Combine framework lets us model all sorts of asynchronous events and operations as “values over time”. While that’s a phrase that’s commonly used within the reactive programming world, as a concept and way of constructinglogic, it
OBSERVERS IN SWIFT
Observers in Swift - Part 1. observers. design patterns. Swift 5.0. Published on 15 Apr 2018. Often when building apps, we find ourselves in situations when we need to set up a one-to-many relationship between objects. It can be when multiple objects want to react to changes in the same state, or when a certain event needs to bebroadcasted to
SWIFT CLIP: KEY PATHS AND FUNCTIONS Let’s take a look at how Swift’s key paths work, and how they relate to functions — both in terms of what comes built into the language itself, and what kind of utilities that we can write ourselves to form some really nice convenience APIs. FORMATTING NUMBERS IN SWIFT Solving the decimal problem. At the most basic level, creating a textual representation of a given number simply involves initializing a String with it, which can either be done directly, or by using a string literal:. let a = String (42) // "42" let b = String (3.14) // "3.14" let c = " \(42), \(3.14) " // "42, 3.14". However, while that approach might work well for generating simpler INTEGRATION TESTS IN SWIFT The integration of multiple units. Any code base can usually be separated into different parts — both by high-level features, such as Search, Login, Networking, and so on — and at a much lower level, by looking at individual classes and functions.A common way to test all those different parts is to do unit testing, and test each part (or unit) in isolation.PREDICATES IN SWIFT
In Swift, operator implementations are just normal functions that take their operands as arguments (in this case a left-hand side one, and a right-hand side one). Using the above, we can now create matching predicates like this: let uncompletedItems = list. items (matching: \. isCompleted == false) That’s pretty cool! CONSTRUCTING URLS IN SWIFT Most modern apps require some form of networking - which means working with URLs in different shapes and forms. However, constructing URLs - especially dynamic ones based on user input - isn't always straight forward, and can lead to a wide range of bugs and problems if we'renot careful.
THE POWER OF KEY PATHS IN SWIFT The basics. Key paths essentially let us reference any instance property as a separate value. As such, they can be passed around, used in expressions, and enable a piece of code to get or set a property without actually knowing which exact property its working with. GRAND CENTRAL DISPATCH Grand Central Dispatch. In Swift we have a few different options available to us when it comes to asynchronous programming — code that doesn’t immediately execute as part of our program’s main control flow, but rather is dispatched onto a different queue of execution. Grand Central Dispatch (or GCD for short) is one suchoption — and is
BINDABLE VALUES IN SWIFT Arguably one of the most challenging aspects of building apps for most platforms is making sure that the UI we present to the user always remains in sync with our underlying data models, and many techniques have been invented in order to address this problem. This week, let’s take a look at one such technique, that involves binding our model values to our UI. Articles, podcasts and news about Swift development, by John Sundell.
* Articles
* Podcast
* Videos
* Discover
* Sponsorship
* About
* Search
INSTABUG: Whether it’s crashes, slow screen transitions, or unresponsive UIs — Instabug automatically gives you all of the logs you need to fix bugs and issues. Get started now.* RSS feed
* Categories
FEATURED
* Get ready for WWDC 97: “ANYTHING CAN HAPPEN DURING WWDC” WITH SPECIAL GUEST ISHSHABAZZ
* Concurrency
SWIFT CLIP: DISPATCH QUEUES Writing asynchronous code using dispatch queues and work items. * Swift fundamentals SORTING SWIFT COLLECTIONS Covers both the basics, as well as increasingly advanced techniques.RECENTLY PUBLISHED
Show compact list
*
A SWIFT DEVELOPER’S WWDC DREAMS - 2021 EDITION* before wwdc
* wishlist
Published on 03 Jun 2021 With the start of WWDC21 just around the corner, I’d like to continue the tradition that I started in 2019 , and share some of my biggest hopes and dreams for this year’s edition of the conference. Note that these are really not _predictions_, nor are they based on any kind of insider information. It’s just me sharing some of my personal Swift-related WWDC dreams with you. INSTABUG: Whether it’s crashes, slow screen transitions, delayed network calls, or unresponsive UIs — Instabug automatically gives you all of the logs you need to fix bugs and issues, and to ship high-quality apps. Get started now. POWERFUL SWIFTUI CUSTOMIZATION I absolutely love SwiftUI (so much so that I’m _kind of_ porting it to the web ), but that doesn’t mean that it’s perfect. In fact, being just shy of two years old at this point, it’s still a very young framework that has yet to become as feature-complete, flexible and powerful as tools like UIKit andAppKit are.
One of the key improvements that I’d like to see this year — that would unlock a lot of that additional power and flexibility — is for Apple to add proper, fully baked customization APIs to the entire suite of system views that the framework ships with. For example, like we took a look at in “Encapsulating SwiftUI viewstyles” , the
ButtonStyle protocol already enables us to perform very custom, finely grained customization when it comes to how Button views are styled: struct ActionButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View {configuration.label
.foregroundColor(.white) .font(Font.body.bold()).padding(10)
.padding(.horizontal, 20) .background(Color.blue).cornerRadius(10)
}
}
What makes styles defined using the above protocol so powerful is that they can be applied to an entire view hierarchy at once — making it possible to very neatly separate an app’s styling and theming code from the specific logic that’s contained within each individual view. In fact, if we wanted to, we could even style all of the buttons within an entire SwiftUI-based application simply by doing this: @main struct MyApp: App { var body: some Scene {WindowGroup {
RootView().buttonStyle(ActionButtonStyle())}
}
}
However, while SwiftUI already ships with a number of other styling protocols that work the exact same way as ButtonStyle, many of them are currently not available for us third-party developers to implement. Take the NavigationViewStyle protocol, for example. If we take a look at its public definition by command-clicking it in Xcode, all that we’ll see is this: public protocol NavigationViewStyle {}
The same thing is true for other, similar protocols as well — including ListStyle, MenuButtonStyle, PickerStyle, and so on. So, my wish would be for Apple to open up those protocols so that we’ll be able to write custom styles for more or less _any_ built-in SwiftUI view, not just for a few select ones, like Button and Label. I think that could solve many of the styling-related issues that lots of developers (myself included) have faced when adopting SwiftUI within apps that require more custom-looking UIs. For example, the above kind of customization APIs could enable us to style navigation and tab bars, to (finally) be able to remove list cell separators, and to perform other kinds of common tweaks that UIKit and AppKit make super simple, but SwiftUI currently makes close to impossible (without resorting to some form of UIAppearance orsubview hacking).
I think that SwiftUI already has a quite broad coverage when it comes to the _types_ of views that it supports, so (at least from my perspective) it would make a ton of sense for Apple to instead focus on _depth_ this year — to make the views that SwiftUI already offers much more flexible, powerful, and customizable. ASYNC/AWAIT ALL THE THINGS! With concurrency being such a strong focus of Swift 5.5 (which I’ll cover in much more detail once I’ve had a chance to use it to write proper production code), I’d love to see Apple update many of the asynchronous APIs that ship as part of their SDKs to take full advantage of features like async/await. For example, imagine being able to perform a URLSession-based networkcall like this:
let response = try await URLSession.shared.dataTask(for: url) Or to request push notification permissions like this: let center = UNUserNotificationCenter.current() let isAuthorized = try await center.requestAuthorization() While Combine already enables us to perform many kinds of asynchronous tasks in really powerful ways, if Apple were to fully embrace Swift’s new first-class concurrency features, I think that would both serve as great examples for the community to follow, and would make it much easier for us to adopt those features within our own code as well. Plus, those new APIs would very likely be purely additive to the existing ones, meaning that (just like when Combine was introduced) we’d be able to migrate to them piece-by-piece, at our own pace.INTERACTIVE WIDGETS
To say that iOS 14’s introduction of WidgetKithas
turned out to be successful is almost an understatement — with the new home screen widgets reaching very widespread adoption, not just among developers and tech enthusiasts, but also within the wider iOS user base (in big part thanks to the incredible work by Widgetsmithcreator David
Smith, who I had the true pleasure of talking to on the podcasta while back).
However, in their current shape, widgets are quite limited in terms of what kinds of user interactions that they can accept — with deep links into the host application being the only real way to implement custom interaction logic. Now, I completely understand _why_ Apple made that decision. After all, like Eliza Block explained when she was a guest on the podcast last year , a widget’s UI isn’t actually constantly running on the home screen, but is rather rendered by the system based on serialized snapshots that are stored on disk, mostly for performance and energy efficiency reasons. So if the system is essentially rendering all widgets as completely static view hierarchies that are computed up-front (by a widget’s backing TimelineProvider), how could Apple enable us to write custom interaction code within that context, without fundamentally changing the way widgets work? One idea that comes to mind is that some form of event-based message-passing system could be introduced, that would enable a given widget’s timeline entry views to trigger custom events, for example using something like a built-in EventButton: struct ArticleWidgetEntryView: View { var entry: ArticleEntry var body: some View { VStack(alignment: .leading, spacing: 5) { Text(entry.article.title).bold()
Text(entry.article.description) .foregroundColor(.secondary).font(.footnote)
EventButton(
systemImage: "heart.fill", event: ArticleWidget.Event.toggleFavorite)
}
.padding()
}
}
Since the above doesn’t involve executing any arbitrary view-level code in response to user interactions, it would still let the system remain in complete control over the rendering and lifecycle of allwidget UIs.
Because WidgetKit is Swift(UI)-only, the above Event type could then very likely be referenced by both the main Widget definition, and its TimelineProvider, in a completely type-safe way — rather than having to pass either raw strings or userInfo-style dictionaries around. For example, perhaps the TimelineProvider protocol (or a specialized version of it) could gain a new method that would be passed any Event that was triggered (as well as the entry that triggered it), which in turn would let us run completely custom code in response to that, while still enabling the system to keep using its snapshot-based rendering strategy.ROCK-SOLID TOOLING
Although the overall quality of Swift’s tooling and the way it’s integrated into Xcode has certainly improved since when the language was first introduced, it remains one of the most significant drawbacks of Swift as a whole. It’s still, in 2021, very common for autocomplete to completely stop working, for syntax highlighting to disappear, and for obscure error messages to be shown when a compilation failure occurred — even within relatively simpleprojects.
I realize that these are not easy problems to solve, especially given Swift’s overall complexity and very rapid evolution, but if I could just pick a single item from this list of dreams, then it’d be this one. There’s just so many things to like about Swift, UIKit, SwiftUI, and the rest of Apple’s frameworks and SDKs, and for all of its flaws, I think that Xcode is actually a quite fantastic development environment overall — I just _really wish_ that the basic editing experience would get elevated to the very high level of quality that I’ve come to expect from Apple products. That’s not to say that _all_ of Swift’s tooling is flawed. Take the Swift Package Manager for example — overall, it’s _by far_ the most stable and easy-to-use dependency management system that I’ve ever used (and I don’t mean that as an insult to any of the other package managers out there). Basically, when using SwiftPM, dependencymanagement
has
mostly become a solved problem, at least for me and the teams that I work with. It’s fast, reliable, and powerful. The same thing can now also be said for Xcode’s new build system, and many other parts of the overall experience of developing apps for Apple’s platforms. So, what I’m hoping for is for some of the rough edges to be smoothened out, and I’m sure that we’ll get there one day. Let’s see if Xcode 13’s release day will be that day. REMAINING 2020 DREAMS Finally, I’d also still love to see some of my remaining 2020 dreamseventually become
reality.
XCODE ON IPAD
is
something that I’ve long been wishing for. I know that not _everyone_ wants to write code on an iPad, but I really do, especially when traveling or when working outside. That doesn’t mean that I’d stop using my M1 Mac mini if an iPad version of Xcode would be released next week — it would just mean that I’d have an additional device that I, and others, could build apps and librarieson.
Swift Playgrounds is an amazing tool for learning, prototyping and experimentation — but it’s not an IDE for building proper apps and Swift packages, and it was never intended to be. I think at this point in its lifecycle, the iPad should become a computing platform that’s not just capable of _running apps_ — it should also enable us to _build and deploy them_.END-TO-END SWIFT
, or
some form of Swift-based cloud functions, was also one of my 2020 dreams. So many apps need to run server-side logic, but not all of them _really_ need a completely custom server. Sure, there are lots of third-party tools available that lets us deploy individual pieces of logic, such as Cloudflare Workers (which is what powers this site’s search feature), but it would be incredible to see a completely integrated, Swift-based server-less system from Apple that would let us accomplish similar things. I’d also still very much like to be able to USE THE SWIFT PACKAGE MANAGER TO DEFINE ENTIRE APP PROJECTS,
rather than just libraries and command line tools. Like I mentioned earlier, SwiftPM is one of my favorite parts of Swift’s overall toolchain, so I’d be delighted to see it expand to cover even more use cases this year. Support Swift by Sundell by checking out this sponsor: INSTABUG: Whether it’s crashes, slow screen transitions, delayed network calls, or unresponsive UIs — Instabug automatically gives you all of the logs you need to fix bugs and issues, and to ship high-quality apps. Get started now.CONCLUSION
Those are my biggest Swift-related dreams for WWDC21. What do you think? Do you share some of my dreams, or are there any other Swift-related announcements that you’d like to see next week? Let me know via either Twitter or email.
If you enjoyed this article, then make sure to check out WWDC by Sundell & Friends , on which I and some of my friends will cover WWDC21 in great detail all throughout the weekof the conference.
Thanks for reading!
*
* Listen to a wishlist podcast episode 14: “HOLIDAY SPECIAL” WITH SPECIAL GUESTS TOBIAS DUE MUNK, NATALIYA PATSOVSKA & PATRICK BALESTRA * Listen to a before wwdc podcast episode 97: “ANYTHING CAN HAPPEN DURING WWDC” WITH SPECIAL GUEST ISHSHABAZZ
* Read more before wwdc articles A SWIFT DEVELOPER’S WWDC DREAMS - 2020 EDITION My biggest dreams for WWDC20.*
PODCAST: “AN ENTIRE SPECTRUM OF APPS” WITH SPECIAL GUEST SEANALLEN
* swiftui
* architecture
* project management Published on 31 May 2021 Listen using: Apple PodcastsOvercast
Castro
Casts RSS
Sean Allen returns to the show to talk about using the MVVM design pattern within SwiftUI-based apps, building a course around MapKit and CloudKit, how to approach all of the new material that WWDC has to offer, and what goes into making a really great developer portfolio.SPONSORS
* NORDVPN : Make your Internet connection private and secure, no matter which network that you’re on, and unlock your video streaming services. Get a massive discount on their two-year plan, and an extra free month, at nordvpn.com/sundell . * MACSTADIUM : The leading provider of cloud solutions built on real Mac hardware. Get started at macstadium.com/sundell .LINKS
* Sean on Twitter
* John on Twitter
* Sean’s new course: Dub Dub Grub * Sean’s YouTube channel* CloudKit
* Dribbble
* Behance
* Sean’s MVVM video * Different flavors of view models in Swift * The SwiftUI environment API * Stack Overflow answer about SwiftUI and view models * The factory pattern * The recent episode with David Smith * WWDC by Sundell & Friends * Sean’s most recent portfolio review video * Intro and outro music by Dariusz Dziuk*
*
DISCOVER SWIFTUI
Get the most out of Apple’s new UI framework. * Read more about swiftui LEARNING SWIFTUI BY BUILDING TOOLS AND PROTOTYPES A great way to get started. * Another article about architecture LIGHTWEIGHT PRESENTERS IN SWIFT*
Support Swift by Sundell by checking out this sponsor: INSTABUG: Whether it’s crashes, slow screen transitions, delayed network calls, or unresponsive UIs — Instabug automatically gives you all of the logs you need to fix bugs and issues, and to ship high-quality apps. Get started now.*
AVOIDING PROBLEMATIC CASES WHEN USING SWIFT ENUMS* enums
* language features
* code structure
Published on 27 May 2021BASICS ARTICLE AVAILABLE: Enums Swift’s implementation of enums is, without a doubt, one of the most beloved and powerful features that the language has to offer. The fact that Swift enums go way beyond simple enumerations of integer-based constants, and support things like associated values and sophisticated pattern matching, makes them a great candidate for solving many different kinds of problems. However, there are certain kinds of enum cases that can arguably be good to avoid, as they could lead us to some tricky situations, or make our code feel less “idiomatic” that what we intended. Let’s take a look at a few such cases and how they could be refactored using some of Swift’s other language features. INSTABUG: Whether it’s crashes, slow screen transitions, delayed network calls, or unresponsive UIs — Instabug automatically gives you all of the logs you need to fix bugs and issues, and to ship high-quality apps. Get started now. REPRESENTING THE LACK OF A VALUE As an example, let’s say that we’re working on a podcast app, and that we’ve implemented the various categories that our app supports using an enum. That enum currently contains cases for each category, as well as two somewhat _special_ cases that’s used for podcasts that don’t have a category at all (none), as well as a category that can be used to reference all categories at once (all): extension Podcast { enum Category: String, Codable {case none
case all
case entertainment
case technology
case news
...
}
}
Then, when implementing features such as filtering, we can use the above enum to perform pattern matching against the Category value that the user selected within the UI (which is encapsulated within a Filtermodel):
extension Podcast { func matches(filter: Filter) -> Bool { switch filter.category { case .all, category: return name.contains(filter.string)default:
return false
}
}
}
At first glance, the above two pieces of code might look perfectly fine. But, if we think about it, the fact that we’ve currently added a specific none case for representing the lack of a category is arguably a bit strange, given that Swift does have a built-in language feature that’s tailor-made for that purpose — _optionals_. So, if we instead were to turn our Podcast model’s category property into an optional, then we’d get support for representing missing categories completely for free — plus we could now leverage all of the features that Swift optionals support (such as if let statements) when dealing with such missing values:struct Podcast {
var name: String
var category: Category?...
}
Something that’s really interesting about the above change is that any exhaustive switch statements that we were previously using on Podcast.Category values will still keep working just as they did before — since it turns out that the Optional type itself is also, in fact, an enum that uses a none case to represent the lack of a value — meaning that code like the following function can remain completely unchanged (apart from modifying its argument to be an optional): func title(forCategory category: Podcast.Category?) -> String {switch category {
case .none:
return "Uncategorized"case .all:
return "All"
case .entertainment: return "Entertainment"case .technology:
return "Technology"case .news:
return "News"
...
}
}
The above works thanks to a bit of Swift compiler magic that automatically flattens optionals when they’re used in pattern matching contexts (such as switch statements), which lets us both address cases within the Optional type itself, as well as cases defined within our own Podcast.Category enum, all within the samestatement.
If we wanted to, we could’ve also used case nil instead of case .none, since those are functionally identical in the above type ofsituation.
DOMAIN-SPECIFIC ENUMS Next, let’s turn our attention to our Podcast.Category enum’s all case, which is also a bit strange if we think about it. After all, a podcast can’t belong to all categories simultaneously, so that all case really only makes sense within the context of filtering. So, rather than including that case within our main Category enum, let’s instead create a dedicated type that’s specific to the domain of filtering. That way, we can achieve a quite neat separation of concerns, and since we’re using nested types, we can have our new enum use the same Category name, only this time it’ll be nested within our Filter model — like this: extension Filter {enum Category {
case any
case uncategorized
case specific(Podcast.Category)}
}
Worth noting is that we _could’ve_ chosen to use the optional approach here as well, with nil representing either any or uncategorized, but since there are two potential candidates in this case, we’re arguably making our intent much more clear by using dedicated cases here. What’s really nice about the above approach is that we can now implement our entire filtering logic using Swift’s pattern matching capabilities — by switching on the filtered category and by then using where clauses to attach additional logic to each case: extension Podcast { func matches(filter: Filter) -> Bool { switch filter.category { case .any where category != nil, .uncategorized where category == nil, .specific(category): return name.contains(filter.string)default:
return false
}
}
}
With all of the above changes in place, we can now go ahead and remove the none and all cases from our main Podcast.Category enum — leaving us with a much more straightforward list of each of the categories that our app supports: extension Podcast { enum Category: String, Codable {case entertainment
case technology
case news
...
}
}
CUSTOM CASES AND CUSTOM TYPES When it comes to enums like Podcast.Category, it’s incredibly common to (at some point) introduce some kind of custom case that can be used to handle one-off cases, or to provide forward compatibility by gracefully handling cases that might be added server-side in thefuture.
One way to implement that would be to use a case that has an associated value — in our case a String representing the raw value of a custom category, like this: extension Podcast { enum Category: Codable {case all
case entertainment
case technology
case news
...
case custom(String)}
}
Unfortunately, while associated values are incredibly useful in other contexts, this is not really one of them. First of all, by adding such a case, our enum can no longer be String-backed, meaning that we’ll now have to write custom encoding and decoding code, as well as logic for converting instances to and from raw strings. So let’s explore another approach instead, by converting our Category enum into a RawRepresentable struct, which once again lets us leverage Swift’s built-in logic for encoding, decoding, and handling string conversions for such types: extension Podcast { struct Category: RawRepresentable, Codable, Hashable { var rawValue: String}
}
Since we’re now free to create Category instances from any custom string that we want, we can easily support both custom and future categories without requiring any additional code on our part. However, to make sure that our code remains backward compatible, and to make it easy to refer to any of our built-in, currently known categories — let’s also extend our new type with static APIs that’ll achieve all of those things: extension Podcast.Category { static var entertainment: Self { Self(rawValue: "entertainment")}
static var technology: Self { Self(rawValue: "technology")}
static var news: Self { Self(rawValue: "news")}
...
static func custom(_ id: String) -> Self {Self(rawValue: id)
}
}
Although the above change did require _some_ amount of extra code to be added, we’ve now ended up with a much more flexible setup that’s almost entirely backward compatible. In fact, the only updates that we need to make are to code that performs exhaustive switches on Category values. For example, the title function that we took a look at earlier previously switched on such a value to return a title matching a given category. Since we can no longer get an exhaustive list of each Category value at compile-time, we’d now have to use a different approach to compute those titles. In this particular case we could, for example, see this as an excellent opportunity to move those strings to a Localizable.strings file, and then resolve our titleslike this:
func title(forCategory category: Podcast.Category?) -> String { guard let id = category?.rawValue else { return NSLocalizedString("category-uncategorized", comment: "")}
let key = "category-\(id)" let string = NSLocalizedString(key, comment: "") // Handling unknown cases by returning a capitalized version // of their key as a fallback title: guard string != key else { return key.capitalized}
return string
}
Another option would be to resolve our localized titles within the Category type itself, and to perhaps also add an optional title property which would enable our server to send pre-localized titles for custom categories that our app doesn’t yet natively support. AUTO-NAMED STATIC PROPERTIES As a quick bonus tip, one downside of the above struct-based approach is that we now have to manually define the underlying string raw values for each of our static properties, but that’s something that we could solve using Swift’s #function keyword. Since that keyword will be automatically replaced by the name of the function (or, in our case, property) that its encapsulating function is being called from, that’ll give us the same automatic raw value mapping as when usingan enum:
extension Podcast.Category { static func autoNamed(_ rawValue: StaticString = #function) -> Self { Self(rawValue: "\(rawValue)")}
}
With the above utility in place, we can now simply call autoNamed() within each of our built-in category APIs, and Swift will automatically fill in those raw values for us: extension Podcast.Category { static var entertainment: Self { autoNamed() } static var technology: Self { autoNamed() } static var news: Self { autoNamed() }...
static func custom(_ id: String) -> Self {Self(rawValue: id)
}
}
Worth noting, though, is that we have to be a bit careful not to rename any of the above static properties when using that #function-based technique, since doing so will also change the underlying raw value for that property’s Category. However, that’s also the case when using enums, and on the flip side, we’re now also preventing typos and other mistakes that can happen when defining each raw string manually. Support Swift by Sundell by checking out this sponsor: INSTABUG: Whether it’s crashes, slow screen transitions, delayed network calls, or unresponsive UIs — Instabug automatically gives you all of the logs you need to fix bugs and issues, and to ship high-quality apps. Get started now.CONCLUSION
Swift enums are awesome (in fact, I’ve written over 15 articles on that topic alone), but there are certain situations in which another language mechanism might be a better choice for what we’re looking to build, and it’s always possible that we might need to switch between several different mechanisms and approaches as our project grows and evolves. Hopefully, this article has given you a few ideas on how those kinds of situations and problems could be solved, and if you have any questions, comments, or feedback, then feel free to reach out via either Twitter or email.Thanks for reading!
*
* Read more about Swift’s language features CALLING INSTANCE METHODS AS STATIC FUNCTIONS * Another article about code structure STRUCTURING SWIFT CODE * Continue exploring Swift’s language features USING COMPILER DIRECTIVES IN SWIFT Conditional compilation, warnings, errors, and more.*
PODCAST: “ANYTHING CAN HAPPEN DURING WWDC” WITH SPECIAL GUEST ISHSHABAZZ
* before wwdc
* wishlist
* predictions
Published on 21 May 2021 Listen using: Apple PodcastsOvercast
Castro
Casts RSS
Ish ShaBazz returns to the show for a special pre-WWDC episode about what new APIs and developer tools that Apple might announce at this year’s edition of the conference. What’s in store for Swift and SwiftPM, how might UIKit and SwiftUI continue to evolve, and will this be the year when we’ll finally see Apple’s new AR/VR platform?SPONSORS
* INSTABUG : Incredibly useful bug, crash, and performance monitoring for iOS apps. Go to instabug.com/sundell to start your freetrial.
* MACSTADIUM : The leading provider of cloud solutions built on real Mac hardware. Get started at macstadium.com/sundell .LINKS
* Ish on Twitter
* John on Twitter
* Capsicum
* Stacktrace
* The official changelog for Swift 5.5* Actors
* Async/await
* Chained implicit member expressions * Grand Central Dispatch* OperationQueue
* Combine
* TextEditor
* Using the SwiftUI app lifecycle* WidgetKit
* SwiftUI’s state management system* Widgetsmith
* NSHostingView
* ARKit
* Intro and outro music by Dariusz Dziuk*
* Another wishlist episode 14: “HOLIDAY SPECIAL” WITH SPECIAL GUESTS TOBIAS DUE MUNK, NATALIYA PATSOVSKA & PATRICK BALESTRA * Another wishlist episode 63: “IT’S BEEN A WILD YEAR” A HOLIDAY SPECIAL WITH DONNY WALS AND ANTOINE VAN DER LEE * Read more before wwdc articles A SWIFT DEVELOPER’S WWDC DREAMS - 2020 EDITION My biggest dreams for WWDC20.*
Support Swift by Sundell by checking out this sponsor: INSTABUG: Whether it’s crashes, slow screen transitions, delayed network calls, or unresponsive UIs — Instabug automatically gives you all of the logs you need to fix bugs and issues, and to ship high-quality apps. Get started now.*
AVOIDING HAVING TO RECOMPUTE VALUES WITHIN SWIFTUI VIEWS* swiftui
* performance
Published on 20 May 2021DISCOVER PAGE AVAILABLE: SwiftUI In general, using computed properties can be a great way to model view-specific data that we want to create on-demand, when need — especially within SwiftUI views, since each such view already uses a computed property (body) to implement its actual UI. For example, here we’re using two computed properties to determine what title and button text that a UserSessionView should render based on the app’s current LoginState: struct UserSessionView: View { var buttonAction: () -> Void @Environment(\.loginState) private var state var body: some View {VStack {
Text(title)
.font(.headline)
.foregroundColor(.white) Button(buttonText, action: buttonAction).padding()
.background(Color.white).cornerRadius(10)
}
.padding()
.background(Color.blue).cornerRadius(15)
}
private var title: String {switch state {
case .loggedIn(let user): return "Welcome back, \(user.name)!"case .loggedOut:
return "Not logged in"}
}
private var buttonText: String {switch state {
case .loggedIn:
return "Log out"
case .loggedOut:
return "Log in"
}
}
}
To learn more about the Environment property wrapper that’s being used above, check out my guide to SwiftUI’s state management system.
Implementing a SwiftUI view like that, using multiple computed properties, can often be a great approach — as it lets us keep our body implementations as simple as possible, and since it gives us a clear overview of how we’re computing the different content that a given view will render. INSTABUG: Whether it’s crashes, slow screen transitions, delayed network calls, or unresponsive UIs — Instabug automatically gives you all of the logs you need to fix bugs and issues, and to ship high-quality apps. Get started now. RECOMPUTED PROPERTIES But, we also have to keep in mind that computed properties are just that — computed — there’s no form of caching or other kind of in-memory storage involved, meaning that each such values will always be recomputed each time that it’s being accessed. That’s not an issue in our first example, because each of our properties can be quickly computed with constant (or O(1)) time complexity . However, let’s now take a look at another example, which is quite different in terms of performance characteristics, since we’re now computing a property by sorting acollection:
struct RemindersList: View {var items:
var body: some View { List(sortedItems) { reminder in...
}
}
private var sortedItems: { items.values.sorted(by: { $0.dueDate < $1.dueDate})
}
}
On one hand, the above implementation could become quite problematic if the passed items dictionary ends up containing a very large amount of items, since that collection will be re-sorted every single time that we’ll access the sortedItems property. But, on the other hand, it’s a private property that’s only accessed from within our view’s body, and since our view doesn’t have any kind of mutable state, it’s not very likely that our property will actually be accessed that often. However, that could quickly change if we were to add any kind of local state to our view — for example to enable the user to add a new Reminder using an inline TextField: struct RemindersList: View {var items:
var newItemHandler: (Reminder) -> Void @State private var newItemName = "" var body: some View {VStack {
List(sortedItems) { reminder in...
}
HStack {
TextField("Add a new reminder", text: $newItemName)Button("Add") {
newItemHandler(Reminder(name: newItemName))}
.disabled(newItemName.isEmpty)}
.padding()
}
}
private var sortedItems: { items.values.sorted(by: { $0.dueDate < $1.dueDate})
}
}
Now, every time that the user types a new character into the text field, our sortedItems property will be called and our items dictionary will be re-sorted. While that might not _initially_ cause any obvious dips in performance, it’s a very inefficient implementation, and it’s very likely to cause problems at one point or another, especially for users with a large amount of reminders. It’s important to remember that, although SwiftUI does use a type-based diffing algorithm to determine what underlying views to redraw for each state change, and does what it can to ensure that our UI remains performant, it’s not magic — if we write highly inefficient code, there’s not much that SwiftUI can do to fix that. GOING BACK TO THE SOURCE So how can we fix this issue? One way would be to go back to the root source of our items data and update it to perform the necessary sorting right up front. Doing that has two main benefits — one, it lets us perform that operation once, instead of during every single view update, and two, it moves what is essentially a model-level operation into our actual model layer. Big win! Here’s what that could look like if we’re using Combine to load our items through some form of model controller:
func loadItems() -> AnyPublisher<, Error> {controller
.loadReminders()
.map { items in
items.values.sorted(by: { $0.dueDate < $1.dueDate})
}
...
.eraseToAnyPublisher()}
With the above change in place, we can now simply make our RemindersList view accept a pre-sorted array of reminders which we canjust render as-is:
struct RemindersList: View {var items:
...
var body: some View {VStack {
List(items) { reminder in...
}
...
}
}
}
However, while the above approach is certainly preferable in many cases, there might be good reasons why we were modeling our core model collection as a dictionary, rather than using an array, and changing that might not be so simple, or even feasible at all. So let’s also explore a few other options as well. INITIALIZATION LOGIC One way that we could solve our problem at the view level itself is by still having our RemindersList view accept a dictionary, just like before, but to instead perform our sorting within our view’s initializer, rather than using a computed property — for examplelike this:
struct RemindersList: View {var items:
var newItemHandler: (Reminder) -> Voidinit(items: ,
newItemHandler: @escaping (Reminder) -> Void) { self.items = items.values.sorted(by: { $0.dueDate < $1.dueDate})
self.newItemHandler = newItemHandler}
@State private var newItemName = ""...
}
With the above change in place, we’re now only sorting our collection once per RemindersList instance, rather than after every key stroke, without actually having to change the way our view is created or how our app’s data is managed. So while my general recommendation is to keep initializers focused on simple setup work , rather than performing data mutations, that’s a tradeoff that we might be willing to make inthis case.
Worth keeping in mind, though, is that if the parent of our RemindersList view does update (or more specifically, if that parent’s body property gets re-evaluated), then a new instance of our view is likely going to be created, meaning that we’ll once again perform our item sorting operation. Basically, when writing code within SwiftUI views, it’s close to impossible to gain complete control over when and how that code will be executed. After all, a core part of the design of a declarative UI framework like SwiftUI is that the framework takes care of orchestrating all of our UI updates for us. So if we wanted to improve our control over the lifecycle of our actual model logic, then a better approach will likely be to move that logic out from our view implementations and into objects that we have complete control over. DEDICATED MODEL LOGIC One way to do that would be to use something like a view modelto encapsulate
the logic associated with handling our items array. If we then make that view model an ObservableObject, then we’ll be able to easily observe it and connect to it within our SwiftUI views: class RemindersListViewModel: ObservableObject { @Published private(set) var items:init(items: ) {
self.items = items.values.sorted(by: { $0.dueDate < $1.dueDate})
}
func addItem(named name: String) {...
}
}
With the above in place, we can now simplify our view quite heavily, and we’re also free to choose how we want to manage the above RemindersListViewModel ourselves, without having to take view updates and other SwiftUI implementation details into account: struct RemindersList: View { @ObservedObject var viewModel: RemindersListViewModel @State private var newItemName = "" var body: some View {VStack {
List(viewModel.items) { reminder in...
}
HStack {
TextField("Add a new reminder", text: $newItemName)Button("Add") {
viewModel.addItem(named: newItemName)}
.disabled(newItemName.isEmpty)}
.padding()
}
}
}
Very nice! That of course doesn’t mean that every single view within our app now needs to have a view model. It just so happens that in this particular case, a view model turned out to be a quite nice solution to our problem, since it enabled us to move our view-related model logic out from our view hierarchy itself (which also heavily improves that code’s testability). Support Swift by Sundell by checking out this sponsor: INSTABUG: Whether it’s crashes, slow screen transitions, delayed network calls, or unresponsive UIs — Instabug automatically gives you all of the logs you need to fix bugs and issues, and to ship high-quality apps. Get started now.CONCLUSION
Recomputing some of our view-related values every time that a SwiftUI view updates is typically not an issue. After all, that’s the way that each view’s body property works, and as long as those computations can happen quickly (and ideally, with constant time complexity) then we’re not very likely to run into any kind of majorperformance issues.
However, that’s not always the case, and sometimes we might need to be particularly careful with how we consume our model data within our views, especially if doing so involves any kind of potentially heavy operations that could slow down our overall UI performance. Hopefully this article has illustrated my overall approach to solving those kinds of problems, and if you have any questions, comments or feedback, then feel free to reach out via either Twitteror email .
Thanks for reading!
*
* Listen to a podcast episode about performance 27: “EXPONENTIAL OPEN SOURCE EFFECT” WITH SPECIAL GUEST RYANNYSTROM
* Listen to a podcast episode about swiftui 72: “MANY LAYERS OF SWIFTUI” WITH SPECIAL GUEST TOBIAS DUE MUNK * Read more about swiftui APPLYING ROUNDED CORNERS TO A UIKIT OR SWIFTUI VIEW*
THREE WAYS TO RENDER A SWIFTUI VIEW IN A PLAYGROUND* swiftui
* playgrounds
Published on 19 May 2021DISCOVER PAGE AVAILABLE: SwiftUI Although Xcode Previews is quickly becoming the go-to development tool for quick iterations and prototyping when building SwiftUI views, there are still situations when firing up a Swift playground can be the quickest and easiest way to try out a new UI idea. USING UIHOSTINGCONTROLLER One of the ways to render a SwiftUI view within a playground’s live view is to wrap it in a UIHostingController, which can then be assigned to the liveView property of the current PlaygroundPage — for example like this:import SwiftUI
import PlaygroundSupport struct MyExperimentalView: View { var body: some View {...
}
}
let view = MyExperimentalView() let hostingVC = UIHostingController(rootView: view) PlaygroundPage.current.liveView = hostingVCCALLING SETLIVEVIEW
Although the above setup is not super verbose by any stretch of the imagination, it turns out that there’s an even simpler way to perform the above liveView assignment — and that’s by using the setLiveView method, which essentially performs the exact same UIHostingController wrapping that we did above, but in a way that doesn’t require any additional code on our part:import SwiftUI
import PlaygroundSupport struct MyExperimentalView: View { var body: some View {...
}
}
let view = MyExperimentalView() PlaygroundPage.current.setLiveView(view) PINNING VIEWS TO A PLAYGROUND’S TIMELINE While both of the above two methods work great in many different kinds of situations, it’s definitely possible to encounter various kinds of SwiftUI errors that seem to only happen when rendering a view within a playground. Thankfully, if you ever do encounter any of those errors, there’s a third option that can be surprisingly powerful. A feature that Swift playgrounds have supported since day one is that any value can be pinned to a playground’s timeline, which enables us to visualize the outcomes of our expressions in various ways. In the case of SwiftUI views, pinning a View expression actually results in that view being rendered inline, right within Xcode’s code editor. For example, if we pin our above MyExperimentalView() expression by using the rectangular icon in the timeline on the right, it’ll now be rendered inline like this: What’s especially cool about this last technique is that it enables us to render multiple views at the same time, just like we can when using Xcode’s Preview feature.CONCLUSION
So, there you have it. Three different ways to render a SwiftUI view within a playground. I still use playgrounds almost every single day. As someone who experiments a lot with both UI development and other Swift techniques, I find playgrounds to be an incredibly convenient tool, since I don’t have to create a whole proper Xcode project just to try out a quick idea.Thanks for reading!
Support Swift by Sundell by checking out this sponsor: INSTABUG: Whether it’s crashes, slow screen transitions, delayed network calls, or unresponsive UIs — Instabug automatically gives you all of the logs you need to fix bugs and issues, and to ship high-quality apps. Get started now.*
*
DISCOVER SWIFTUI
Get the most out of Apple’s new UI framework. * Listen to a podcast episode about swiftui 90: “THE ESSENCE OF APP ARCHITECTURE” WITH SPECIAL GUEST MATTGALLAGHER
* Read more about swiftuiSWIFTUI
A recap of the basics of SwiftUI. Building custom views, modifying existing ones, and managing state.*
Support Swift by Sundell by checking out this sponsor: INSTABUG: Whether it’s crashes, slow screen transitions, delayed network calls, or unresponsive UIs — Instabug automatically gives you all of the logs you need to fix bugs and issues, and to ship high-quality apps. Get started now.*
ESSENTIAL DEVELOPER
* Sponsored
Published on 17 May 2021 My thanks to Caio Zullo and Mike Apostolakis for sponsoring Swift by Sundell to promote Essential Developer and their iOS Career CrashCourse
— a free online course for iOS developers. While many iOS development courses out there are focused on helping beginners learn the fundamentals of app development, this quick crash course is for mid- and senior level developers who wish to improve their skills and advance their career. It touches on topics like refactoring legacy code, avoiding common anti-patterns, composition, and how to keep moving forward in your career. The May edition of the course is starting today, on May 17th, so if you’re reading this article before May 23rd, then simply head over to the Essential Developer website to sign up for this week’s course (it’s completely free!). Or, if you’re reading this at a later point in time, then there will be many future editions of the course as well — all that you have to do is to enter your email here and Caio and Mike will let you know once their next edition isstarting.
*
ASSIGNING AN EXPRESSION TO A VARIABLE WITH THE SAME NAME* language features
Published on 14 May 2021 NEW IN SWIFT 5.4: It’s now possible to create a local variable that’s assigned to an expression that has the same name, without having to manually disambiguate with self. For example, the following ItemListViewController has a method that lets us retrieve an Item for a given IndexPath, which we’ve chosen to simply call item(at:): class ItemListViewController: UIViewController {...
private func item(at indexPath: IndexPath) -> Item {...
}
}
When using Swift 5.3 and earlier, if we wanted to call the above method and assign its result to a local let or var that’s also called item, we’d then have to prefix our method call with self in order for the compiler to be able to separate the two — like this: class ItemListViewController: UIViewController {...
private func showDetailViewForItem(at indexPath: IndexPath) { let item = self.item(at: indexPath)...
}
}
Starting in Swift 5.4, however, that’s no longer required, and the compiler will now automatically understand that the right-hand item symbol refers to a call to our method, regardless of whether we referto it using self:
class ItemListViewController: UIViewController {...
private func showDetailViewForItem(at indexPath: IndexPath) { let item = item(at: indexPath)...
}
}
Perhaps my favorite way of using this new syntax feature is when writing unit tests for asynchronous code, which typically
involves creating XCTestExpectation instances using the built-in expectation API. Because the most natural name for such expectations is often simply expectation, it’s really nice to now be able to dothe following:
class ItemLoaderTests: XCTestCase {...
func testLoadingItem() { let expectation = expectation(description: "Loading item")...
}
}
Another type of situation in which the above feature could come in handy is when we want to create a local, mutable copy of a property. That can now also be done without having to use self when referring to the property that we’re copying — for example like this:struct Item {
var title: String
var prefix: String? var suffix: String? func fullTitle() -> String { var title = title if let prefix = prefix { title = prefix + title}
if let suffix = suffix {title += suffix
}
return title
}
}
Granted, this might not be a revolutionary new syntax feature that will completely change the way we write Swift code — but hey, not every feature or change needs to be. I personally think that these kinds of “quality of life” improvements are incredibly welcome, and can make certain kinds of code feel quite a bit more lightweight. Support Swift by Sundell by checking out this sponsor: INSTABUG: Whether it’s crashes, slow screen transitions, delayed network calls, or unresponsive UIs — Instabug automatically gives you all of the logs you need to fix bugs and issues, and to ship high-quality apps. Get started now.*
* Read more about Swift’s language features FIVE POWERFUL, YET LESSER-KNOWN WAYS TO USE SWIFT ENUMS * Another article about Swift’s language featuresREFLECTION IN SWIFT
* Continue exploring Swift’s language features THE POWER OF KEY PATHS IN SWIFT*
Support Swift by Sundell by checking out this sponsor: INSTABUG: Whether it’s crashes, slow screen transitions, delayed network calls, or unresponsive UIs — Instabug automatically gives you all of the logs you need to fix bugs and issues, and to ship high-quality apps. Get started now.*
INTRODUCING PLOT COMPONENTS: A NEW WAY TO BUILD HTML PAGES USING SWIFT* web development
* open source
Published on 11 May 2021 Today I’m launching a huge update to my suite of Swift static site generation tools — specifically a brand new version of Plot , the library that’s used to generate all of this website’s HTML, which adds a new API for building HTML components in a very SwiftUI-like way. This new version has been in the works for over a year, and has been properly battle-tested in production. In fact, it was used to render the HTML for the article that you’re reading right now! So I couldn’t be more excited to now finally make it publicly available for the entire Swift community. INSTABUG: Whether it’s crashes, slow screen transitions, delayed network calls, or unresponsive UIs — Instabug automatically gives you all of the logs you need to fix bugs and issues, and to ship high-quality apps. Get started now. FROM NODES TO COMPONENTS Up until this point, Plot has been using an API that represents all of the elements and attributes within an HTML page as _nodes_, which can then be composed and combined in various ways. For example, here’s how an array of BlogPost models could be turned into a- -element based feed of blog posts: func makeBlogFeed(containing posts: ) -> Node
.ul(
.class("blog-feed"), .forEach(posts) { post in.li(.article(
.img(.src(post.imageURL)), .h1(.text(post.title)), .p(.text(post.description)), .a("Continue reading", .href(post.url))))
}
)
}
I’m still incredibly happy with the design of the API that’s used above, as it’s in many ways a perfect match for the very hierarchical nature of HTML and XML-based documents — but at the same time, I’ve become increasingly curious to see what a “SwiftUI makeover” of that API could look like. Now, I don’t mean actually using SwiftUI itself to render HTML. Since it’s a closed-sourced project that was developed exclusively for building native views on Apple’s platforms, there’s really no reasonable way for a third party developer (like myself) to use it to render arbitrary HTML strings. However, like we’ve taken a look at in articles like “The Swift 5.1 features that power SwiftUI’s API”, the public
APIs that SwiftUI offers are all implemented using official language features (as of Swift 5.4 when _result builders_ finally became a
proper part of the language). So, rather than attempting to turn SwiftUI into an HTML renderer, I built my own SwiftUI-inspired API that’s been tailor-made for the task of building HTML components. This is what our blog feed from before would look like if we instead implemented it using that new component-based API: struct BlogFeed: Component {var posts:
var body: Component { List(posts) { post inArticle {
Image(post.imageURL)H1(post.title)
Paragraph(post.description) Link("Continue reading", url: post.url)}
}
.class("blog-feed")
}
}
Even though we’re now using a substantially different syntax to render our HTML, the end result will actually be identical to our earlier implementation. What’s really cool, though, is that we no longer need to manually construct elements like theDetails
Copyright © 2024 ArchiveBay.com. All rights reserved. Terms of Use | Privacy Policy | DMCA | 2021 | Feedback | Advertising | RSS 2.0