- Presenting SharePlay activities from your app’s UI
Make it easy for people to start activities from your app’s UI, from the system share sheet, or using AirPlay over AirDrop. After you define one or more SharePlay activities for your app, make them easy for people to discover in your UI. Include buttons, menus items, and other elements to start activities, present activities in system interfaces like the share sheet, and update your activities to take advantage of other system behaviors.
Starting an activity requires an active FaceTime call or Messages conversation. When a conversation is active, you can start an activity right away from your UI. If no conversation is active, the Group Activities framework facilitates starting a conversation as part of starting your activity. Some system features also help you start conversations. For guidance about the best ways to add SharePlay support to your app’s UI, see Human Interface Guidelines > SharePlay.
- Applying Realistic Material and Lighting Effects to Entities
Enhance the appearance of objects in a RealityKit scene with Physically Based Rendering (PBR).
A Material instance describes the surface properties of an entity and controls how RealityKit renders that entity. A PhysicallyBasedMaterial is a type of material that closely approximates the way light bounces off objects in the real world. It creates very realistic rendered objects that look natural when placed into an AR scene. When you import models from USDZ files, RealityKit automatically creates one or more PhysicallyBasedMaterial instances from the PBR material settings in the file. You can also create PBR materials manually, either to change the appearance of an entity loaded from a USDZ file at runtime, or to use PBR rendering with procedurally created entities.
- Implementing Special Rendering Effects with RealityKit Postprocessing
Implementing Special Rendering Effects with RealityKit Postprocessing
In iOS 15 and later, and macOS 12 and later, you can modify RealityKit’s rendered frame buffer before your app displays it by registering a callback function. This sample demonstrates how to create a variety of different postprocess effects for a Realitykit scene using four different technologies:
- Metal kernel functions
- Metal Performance Shaders
- Core Image
- SpriteKit rendering
It also demonstrates how to combine multiple postprocess technologies by using both Metal kernel functions and Core Image filters at the same time. The generated app displays a Reality Composer scene in AR and lets you select different postprocessing effects from a list.
- Design and export native 3D for iOS
A fully native Spline Metal renderer to help you bring 3D to iOS, iPadOS, macOS and visionOS.
- Adding Spatial Persona support to an activity
Update your SharePlay activities to support Spatial Personas and the shared context when running in visionOS.
A person who participates in SharePlay activities on Apple Vision Pro has the option to participate using their Spatial Persona. The system arranges Spatial Personas around the activity content, giving each person a clear view of the content and each other. Each person sees the facial expressions of other participants, what they’re looking at, and where they’re pointing. This experience creates the feeling that they’re in the same physical space interacting with shared content and each other.
To maintain the experience when Spatial Personas are visible, apps share additional information to maintain the shared context for the activity. Because participants can see where others are looking, your app’s content must look the same for everyone. Share any additional information you need to keep everyone’s content in sync visually. For example, synchronize your window’s scroll position to ensure everyone sees the same portion of that window.
You don’t need to define new GroupActivity types specifically to support Spatial Personas. The system automatically displays Spatial Personas for existing activities that take place in a window or volume. However, if you support activities in a Full Space, you need to do additional work to support Spatial Personas for your experience. For information about how to define activities in your app, see Defining your app’s SharePlay activities.
- Supporting Coordinated Media Playback
Create synchronized media experiences that enable users to watch and listen across devices.
Watching TV and movies, and listening to music, can be more fun when you do it with friends and family. However, getting together in person isn’t always an option. Beginning with iOS 15, tvOS 15, and macOS 12, you have the ability to create media apps that let people watch and listen together wherever they are. This capability is possible using AVFoundation and the new GroupActivities frameworks.
AVFoundation introduces a new class, AVPlayerPlaybackCoordinator, that synchronizes the timing of AVPlayer objects across devices. Apps use the GroupActivities framework to connect playback coordinators using a GroupSession object.
- Symbolicating SwiftUI (and any Apple Framework), Part 2
Crash reports and addresses can be scary, so before going any further, let’s take a step back to frame what we are doing. Part 1 showed that Apple’s crash reports have symbols for their frameworks. We also know that a symbol’s address on disk is the same across a device and OS pairing. We want to get all the possible crashes (for a device x OS pair) from Apple and then map the memory address to the symbol name. To do this, we need to reliably calculate a memory address, allowing us to symbolicate crash reports.
Think of this part like we’re doing Algebra. We know the equations for how addresses are calculated. Now, we need to solve for our variables.
First, let’s find the
linker address
, which is defined at the time of compilation and can be found within the binary, making it easy to get. We'll need:- The device
.ipsw
, which you can download it from https://www.ipsw.me - ipsw CLI tool, which lets us extract the framework from .ipsw
brew install blacktop/tap/ipsw
- DyldExtractor to extract the ipsw shared cache
python3 -m pip install dyldextractor
otool
After installing ipsw, our first step is to extract the shared cache:
ipsw extract --dyld PATH_TO_IPSW
Now, we can extract the specific framework binary using DyldExtractor:
dyldex -e /System/Library/Frameworks/YOUR_FRAMEWORK.framework/YOUR_FRAMEWORK ./PATH_TO_EXTRACTED_IPSW/dyld_shared_cache_arm64e
This process isolates our framework binary from the shared cache. The next step involves using otool to determine the linker address. For this, we inspect the load commands and specifically look for the segname __TEXT field in the output.
otool -l binaries/System/Library/Frameworks/SwiftUI.framework/SwiftUI | grep LC_SEGMENT -A8
- The device
- sg.nvim
The official Sourcegraph/Cody plugin for Neovim
- Trigger property observers from initializers in Swift
In Swift, property observers such as
willSet
anddidSet
are not called when a property is set in an initializer. This is by design, as the initializer's purpose is to set up the initial state of an object, and during this phase, the object is not yet fully initialized. However, if we need to perform some actions similar to what we'd do in property observers during initialization, there are some workarounds. - Connecting Xcode To A Running Process
Did you know you can connect the Xcode debugger to a running process? You can also have Xcode wait for a process to launch before connecting. This helps when debugging issues when your App is launched in response to an external event such as a notification. We can also use it to peek at some of the built-in Apps in the simulator.
The steps to connect the debugger to a running process:
- Build and run your App to install it on the simulator or device of your choosing. I find this works fine even with devices connected via WiFi.
- Stop the Xcode debug session. If you want to set some breakpoints for when the App is launched do that now. For example, to inspect the launch options you could set a breakpoint on didFinishLaunchingWithOptions in the App delegate.
- You can either launch the App and then attach the debugger or attach and then launch. Either way use the Xcode Debug menu to attach the debugger to a process.
- If the App is not yet running you will need to attach to it by name. For example, here I am going to attach to the AdaptType project. If the process is not running the Xcode debugger will wait for it to start. This is useful if you want the App to launch in response to an external event such as a notification.
- If the App is already running you can connect to it directly either by name or finding it in the list of running processes. Make sure you have the device or simulator selected as the target of your Xcode project then use the “Attach to Process” option in the Debug menu. Xcode suggests the most likely process based on your current Xcode project and destination or you can find it in the list of running processes.
- Once attached you can debug as usual. The debugger will stop if it hits a breakpoint or you can use the view debugger to inspect the view hierarchy.
- Emerge Tools Symbolicator
Have a crash report coming that won't fully symbolicate? This symbolicator contains symbols for SwiftUI and other private frameworks. Upload or paste your crash data below to symbolicate all addresses.
📋 A full list of supported symbols can be found at our open-source ETSymbolication repo.
📚 Read our posts exploring how we uncovered hidden symbols + built an open-source symbolication reference.
🍎 Check out the open source repo to learn how to contribute more symbols to this tool
- Proceedings of the Sixth International Conference on Applied Category Theory 2023
The Sixth International Conference on Applied Category Theory took place at the University of Maryland on 31 July - 4 August 2023, following the previous meetings at Leiden (2018), Oxford (2019), MIT (2020, fully online), Cambridge (2021) and Strathclyde (2022). It was preceded by the Adjoint School 2023 (24 - 28 July), a collaborative research event in which junior researchers worked under the mentorship of experts. The conference comprised 59 contributed talks, a poster session, an industry showcase session, four tutorial sessions and a session where junior researchers who had attended the Adjoint School presented the results of their research at the school. Information regarding the conference may be found at https://act2023.github.io/.
- dyld-shared-cache-extractor
A CLI for extracting libraries from Apple's dyld shared cache file
As of macOS Big Sur, instead of shipping the system libraries with macOS, Apple ships a generated cache of all built in dynamic libraries and excludes the originals. This tool allows you to extract these libraries from the cache for reverse engineering.
- Choosing the right way to hide a view
Control whether a view exists, and how that affects the overall layout.
If your design has views that aren’t always relevant, you have a choice about how their absence affects the overall layout. You can lay out all the other content as if the view doesn’t exist, then update the position of the other content when the view becomes visible. Or, you can reserve space for the view regardless of whether it’s visible, so that when it becomes visible, none of the other content needs to move to accommodate it.
- Unison Cloud Onboarding
Let's get started! If you have any trouble with these instructions or have questions after getting going, we're here to help:
- The
#cloud
channel on Discord is a place to follow Unison Cloud news and updates, get help, and find tips and tricks. - The chat widget in the corner of unison.cloud is monitored by the Unison Cloud team and is another place you can get help.
- For general Unison language questions and announcements, visit the Unison Slack. Bug reports, feature requests, ideas, and feedback are most welcome on any of these channels. The Discord and Slack are also nice places to meet other folks using Unison + Unison Cloud. It's a friendly and supportive group!
- The
- Your Smart TV Knows What You’re Watching
Here’s how to turn off “automated content recognition,” the Shazam-like software on smart TVs that tracks what you’re watching.
- GlobalActor
A type that represents a globally-unique actor that can be used to isolate various declarations anywhere in the program.
A type that conforms to the
GlobalActor
protocol and is marked with the@globalActor
attribute can be used as a custom attribute. Such types are called global actor types, and can be applied to any declaration to specify that such types are isolated to that global actor type. When using such a declaration from another actor (or from nonisolated code), synchronization is performed through the shared actor instance to ensure mutually-exclusive access to the declaration. - The Reference Book of RealityKit
Reality Kit for making AR apps on iOS.
In this article, you can learn how to use RealityKit from basic to advanced.
Please use it as an introduction and an index.
- TESTS ARE DEAD.
METICULOUS AI
IS HERE.Cover the 1000s of edge cases of your application - in 5 minutes of setup, with zero maintenance.
- GitHub Markdown Alerts
Alerts are an extension of the blockquote syntax that you can use to emphasize critical information. On GitHub, they are displayed with distinctive colors and icons to indicate the importance of the content.
> [!NOTE] > Highlights information that users should take into account, even when skimming. > [!TIP] > Optional information to help a user be more successful. > > [!IMPORTANT] > Crucial information necessary for users to succeed. > > [!WARNING] > Critical content demanding immediate user attention due to potential risks. > > [!CAUTION] > Negative potential consequences of an action.
Note
Highlights information that users should take into account, even when skimming.
Tip
Optional information to help a user be more successful.
Important
Crucial information necessary for users to succeed.
Warning
Critical content demanding immediate user attention due to potential risks.
Caution
Negative potential consequences of an action.
- emoji-cheat-sheet
This cheat sheet is automatically generated from GitHub Emoji API and Unicode Full Emoji List.
- 📺 Introducing Apple Vision Pro
The era of spatial computing is here, where digital content blends seamlessly with your physical space. So you can do the things you love in ways never before possible. This is Apple Vision Pro.
- MachO's Other Tool
mootool
is an attempt at an open source replacement to the legandaryjtool2
allowing it to continue to progress with the Apple research community. Ruby was selected as Homebrew maintains a good Mach-O parser that is pure (meaning it needs no dependencies other then a Ruby runtime).As a secondary goal every command should provide output both in human readable as well as machien readable (YAML) format making it suitable for use in scripting.
- Namespace
A dynamic property type that allows access to a namespace defined by the persistent identity of the object containing the property (e.g. a view).
- Upcoming third-party SDK requirements
Third-party software development kits (SDKs) can provide great functionality for apps; they can also have the potential to impact user privacy in ways that aren’t obvious to developers and users. As a reminder, when you use a third-party SDK with your app, you are responsible for all the code the SDK includes in your app, and need to be aware of its data collection and use practices. At WWDC23, we introduced new privacy manifests and signatures for SDKs to help bring more awareness for how third-party SDKs use data. This functionality is a step forward for all apps, and we encourage all SDKs to adopt it to better support the apps that depend on them.
Privacy Manifests
Privacy manifest files outline the privacy practices of the third-party code in an app, in a single standard format. When you prepare to distribute your app, Xcode will combine the privacy manifests across all the third-party SDKs used by your app into a single, easy-to-use report. With one comprehensive report that summarizes all the third-party SDKs found in an app, it will be even easier for you to create more accurate Privacy Nutrition Labels.
Signatures for SDKs
Now with signatures for SDKs, when you adopt a new version of a third-party SDK in your app, Xcode will validate that it was signed by the same developer, improving the integrity of your software supply chain.
SDKs that require a privacy manifest and signature
The following are commonly used SDKs in apps on the App Store. Starting in spring 2024, you must include the privacy manifest for any SDK listed below when you submit new apps in App Store Connect that include those SDKs, or when you submit an app update that adds one of the listed SDKs as part of the update. Signatures are also required in these cases where the listed SDKs are used as binary dependencies. Any version of a listed SDK, as well as any SDKs that repackage those on the list, are included in the requirement.
- Plain Swift
Plain Swift is a simple development environment that allows you to develop executables and dynamic libraries using the Swift programming language. It supports syntax highlighting, error highlighting, inline code suggestions, and archiving the compiled product for distribution along with the necessary runtime libraries.
- A Flexible Type System for Fearless Concurrency
This paper proposes a new type system for concurrent programs, allowing threads to exchange complex object graphs without risking destructive data races. While this goal is shared by a rich history of past work, existing solutions either rely on strictly enforced heap invariants that prohibit natural programming patterns or demand pervasive annotations even for simple programming tasks. As a result, past systems cannot express intuitively simple code without unnatural rewrites or substantial annotation burdens. Our work avoids these pitfalls through a novel type system that provides sound reasoning about separation in the heap while remaining flexible enough to support a wide range of desirable heap manipulations. This new sweet spot is attained by enforcing a heap domination invariant similarly to prior work, but tempering it by allowing complex exceptions that add little annotation burden. Our results include: (1) code examples showing that common data structure manipulations which are difficult or impossible to express in prior work are natural and direct in our system, (2) a formal proof of correctness demonstrating that well-typed programs cannot encounter destructive data races at run time, and (3) an efficient type checker implemented in Gallina and OCaml.
- Recruiter Response AI
Answers common recruiter & interview questions.
- Tracking preregistered images in 3D space
Place content based on the current position of a known image in a person’s surroundings.
Use ARKit’s support for tracking 2D images to place 3D content in a space. ARKit provides updates to the image’s location as it moves relative to the person. If you supply one or more reference images in your app’s asset catalog, people can use a real-world copy of that image to place virtual 3D content in your app. For example, if you design a pack of custom playing cards and provide those assets to people in the form of a real-world deck of playing cards, they can place unique content per card in a fully immersive experience.
- Creating 3D objects from photographs
Creating 3D objects from photographs
In iOS 17 and later, and macOS 12 and later, to create a 3D object from a series of photographs, submit the images to RealityKit using a PhotogrammetrySession, register to receive status updates, and start the session. The completed process produces a 3D representation of the photographed object that you can use in your app or export to other software like Reality Composer.
For more information on capturing high-quality images for photogrammetry, see Capturing photographs for RealityKit Object Capture.
- Joker
Deprecated! The functionality of joker is now built-in to Jtool2 when used with --analyze on any kernelcache
Joker is a quick and dirty iOS kernelcache handling utility I've written to assist in my reverse engineering. Apple tries their damn hardest to make reversing the kernel as hard as possible: With every release, more symbols are stripped. The kernelcache, being prelinked, requires less symbols to begin with (and tables in memory, as all LINKEDIT segments, are jettisoned). And - let's not forget - the kernelcache is encrypted. 32-bit kernelcaches can be decrypted thanks to the holy work by @xerub and others, but no 64-bit kernelcache keys exist (publicly), and the only way to "see" the kernel is by dumping it.
- visualEffect3D(_:)
Applies effects to this view, while providing access to layout information through a 3D geometry proxy.
- visualEffect(_:)
Applies effects to this view, while providing access to layout information through a geometry proxy.
- GeometryReader3D
A container view that defines its content as a function of its own size and coordinate space.
This view returns a flexible preferred size to its own container view.
This container differs from GeometryReader in that it also reads available depth, and thus also returns a flexible preferred depth to its parent layout. Use the 3D version only in situations where you need to read depth, because it affects depth layout when used in a container like a ZStack.
- Placing content on detected planes
Detect horizontal surfaces like tables and floors, as well as vertical planes like walls and doors.
Flat surfaces are an ideal place to position content in an app that uses a Full Space in visionOS. They provide a place for virtual 3D content to live alongside a person’s surroundings. Use plane detection in ARKit to detect these kinds of surfaces and filter the available planes based on criteria your app might need, such as the size of the plane, its proximity to someone, or a required plane orientation.
- Marbla
Marbla is an experimental display typeface exploring the possibilities of variable fonts to change the mood and personality of a typeface. Starting with a friendly regular style the letterforms can be modified via the axes Inktrap, Balloon and Curve. The result is a variable font with a range of expressive and playful display styles that can be combined with the legible Regular. The combination of the three axes creates countless possibilities of variation.
- Calling Private APIs in iOS
We will dive into the dark depths of the Objective-C runtime to perform acts forbidden in Swift. So, don’t be scared - the Dynamic Funtime™️ of Objective-C allows us to use an old friend, NSInvocation, which isn’t available to Swift.
- Find API To Invoke
- Import a Bundle
- Create a Class Type
- NSInvocation
- Run on your Device
Searching for iOS Headers
- MeshResource
A high-level representation of a collection of vertices and edges that define a shape.
generateBox(size:majorCornerRadius:minorCornerRadius:)
Creates a new box with rounded corners mesh with the specified extent.
- How to import Swift macros without using Swift Package Manager
Swift Macros are a powerful new feature introduced in Swift 5.9 that allows developers to generate code at compile time. They are a great way to reduce boilerplate code and help scale your codebase by leveraging the power of metaprogramming.
Due to the way they are implemented and their tight coupling with SPM, Swift macros are usually defined in Swift packages and, as such, they are usually imported into Xcode projects such as iOS apps or frameworks as SPM dependencies.
While this is fine in most cases, there are certain situations where you might not want or be able to import the macro as a Swift package dependency. For example, you might want to use a macro in a CocoaPods library or obfuscate its source code.
In these cases, and as I will show you in this article, you might want to import your macro into your Xcode project as a binary instead and not as an SPM dependency.
- Play an animation in RealityKit
Learn how to play animation on 3D models using RealityKit.
When we design augmented reality experiences, a crucial step involves specifying animated behaviors for objects. This will add layers of interactivity, transforming static elements into dynamic components within the augmented environment. In some cases, models may already contain animations, however, we can still define specific behaviors using RealityKit.
- NIO and Swift Concurrency
This article explains how to interface between NIO and Swift Concurrency.
NIO was created before native Concurrency support in Swift existed, hence, NIO had to solve a few problems that have solutions in the language today. Since the introduction of Swift Concurrency, NIO has added numerous features to make the interop between NIO’s Channel eventing system and Swift’s Concurrency primitives as easy as possible.
- visionOS App Icon
A visionOS app icon is circular and includes a background layer and one or two layers on top, producing a three-dimensional object that subtly expands when people view it.
- Configuring your app icon
Add app icon variations to represent your app in places such as Settings, search results, and the App Store.
Every app has a distinct app icon that communicates the app’s purpose and makes it easy to recognize throughout the system. Apps require multiple variations of the app icon to look great in different contexts. Xcode can help generate these variations for you using a single high-resolution image, or you can configure your app icon variations by using an app icon’s image set in your project’s asset catalog. visionOS and tvOS app icons are made up of multiple stacked image layers you configure in your project’s asset catalog.
- moduleAliases
Module aliases for targets in this dependency. The key is an original target name and the value is a new unique name mapped to the name of the .swiftmodule binary.
- Better diff hunk headers with Swift
Step 1: Diff driver
Define a diff driver in your
$HOME/.gitconfig
. Thexfuncname
configuration specifies a regular expression that is used to match a line you want to see in the hunk header after the @@ bit. Covering all possible options with a regexp probably isn't possible, but this should cover most of the cases:[diff "swift"] xfuncname = ^[ \t]*(((private |public |internal |final |open )*class|(private |public |internal )*struct|(private |public |internal )*actor|(private |public |internal )*func|(private |public |internal )*extension|(private |public |internal )*enum)[ \t].*)$
Step 2: Global git attributes
If you don't have a global git attributes file configured, set one up:
git config --global core.attributesfile ~/.gitattributes
Step 3: Configure the swift driver for Swift files
Edit the
~/.gitattributes
file to make Git use your newly defined diff driver for Swift files. Add the following line:*.swift diff=swift
- Join the Mac gaming revolution.
Wine Supercharged... with the power of Apple's Game Porting Toolkit.
- Migrating a test from XCTest
The testing library provides much of the same functionality of XCTest, but uses its own syntax to declare test functions and types. This document covers the process of converting XCTest-based content to use the testing library instead.
- Create an AsyncStream from withObservationTracking() function
I've been wondering if it would be possible to wrap observation into an
AsyncStream
. That would let me use an asynchronousfor
loop to iterate over changes. In this post I will share how I implemented it. - SystemCoordinator
A type you use to coordinate your interface’s behavior when an active SharePlay session supports spatial placement of content.
A
SystemCoordinator
object helps you coordinate the presentation of your app’s content when spatial placement is active. In visionOS, the system can present a SharePlay activity as if the participants were together in the same room with the content. Each participant views the content from a particular vantage point, and sees the changes that others make. The system handles the placement of each participant’s Spatial Persona relative to the content, but you handle any changes to the content itself with the help of theSystemCoordinator
object.You don’t create a
SystemCoordinator
object directly. After you receive aGroupSession
object for an activity, retrieve the system coordinator from the session’ssystemCoordinator
property. When you first retrieve the object, update itsconfiguration
property to tell the system how you want to arrange participants in the scene. After that, use the information in the system coordinator’s properties to keep your app’s interface up to date. When participants support spatial placement, send additional data to synchronize your content for those participants. For example, when one person scrolls the contents of a window, update the scroll position in the window of other spatially aware participants to preserve the shared context for everyone.You choose what information to share among participants, and you choose how to manage the corresponding updates. A system coordinator object only helps you know when to make those changes. Observe the object’s published properties to receive automatic updates when the values change.
- visionOS SharePlay
People expect most visionOS apps to support SharePlay. While wearing Apple Vision Pro, people choose the Spatial option in FaceTime to share content and activities with others.
In a shared activity, FaceTime can show representations of other participants — called Spatial Personas — within each wearer’s space, making everyone feel like they’re sharing the same experience in the same place. During a shared experience in FaceTime, people can interact with each other in natural ways through their Spatial Personas. For example, people can speak or gesture directly to others, tell when someone is paying attention to them, and know which person is using a shared tool or resource.
visionOS uses the concept of shared context to describe the characteristics of a shared activity that help people feel physically present with others while connecting over the same content. A shared context helps give people confidence that they’re experiencing the same thing as everyone else.
When people feel that they’re truly sharing an experience, social dynamics can encourage authentic, intuitive interactions. For example, people can communicate verbally and nonverbally to make plans, take turns, and share resources.
- SpatialTemplatePreference
A structure that specifies the preferred arrangement of participant Spatial Personas in a shared simulation space.
- Peer-to-peer alternatives
Multipeer Connectivity is a high-level interface to Apple’s peer-to-peer Wi-Fi support. It includes:
- A very opinionated networking model, where every participant in a session is a symmetric peer
- User interface components for advertising and joining a session
Use it when your requirements are aligned with those features. Don’t use it if your program uses a client/server architecture; Network framework works better in that case. For an example, see Building a custom peer-to-peer protocol.
Important: A common misconception is that Multipeer Connectivity is the only way to use peer-to-peer Wi-Fi. That’s not the case. Network framework has opt-in peer-to-peer Wi-Fi support. For the details, see Peer-to-Peer networking.
Foundation also has peer-to-peer Wi-Fi support:
- When advertising a service using NSNetService, set the
includesPeerToPeer
property. - To accept connections, set the
.listenForConnections
flag and implement thenetService(_:didAcceptConnectionWith:outputStream:)
delegate callback. - When browsing for services using NSNetServiceBrowser, set the
includesPeerToPeer
property. - After discovering a service with a peer-to-peer enabled browser, connect to that service using
getInputStream(_:outputStream:)
.
These APIs were marked as to-be-deprecated in 2021 (see Versions). If you have existing code that uses them, make a plan to migrate to Network framework.
The dnssd API supports peer-to-peer Wi-Fi but with an important caveat: If you advertise a service on peer-to-peer Wi-Fi using dnssd, the service’s listener must be run by a peer-to-peer aware API, like
NWListener
orNSNetService
. Given that those APIs already have a facility to opt in to peer-to-peer Wi-Fi, there’s very little point using dnssd for this. - TN3151: Choosing the right networking API
Apple platforms have a wide range of networking APIs, spanning many different frameworks:
- Foundation
- Network
- BSD Sockets in the System framework
- And more
With all that choice, it’s hard to know where to start. This technote aims to clarify that. It makes specific recommendations as to which API to use for a given network protocol. It then discusses Alternative APIs and some Best practices.
The focus here is on APIs that allow you to use the networking stack. If you want to extend the networking stack—for example, to add support for a custom VPN protocol—implement a Network Extension provider. For the details, see Network Extension.
- How to customize the macOS menu bar in SwiftUI
In this post, we’ll take a look at how to customize the macOS menu bar for a SwiftUI app, using SwiftUI tools like
CommandMenu
andCommandGroup
. - Spotlight on: Apple Vision Pro apps for enterprise
Businesses of all kinds and sizes are exploring the possibilities of the infinite canvas of Apple Vision Pro — and realizing ideas that were never before possible. We caught up with two of those companies — JigSpace and PTC — to find out how they’re approaching the new world of visionOS.
- UIHostingConfiguration
A content configuration suitable for hosting a hierarchy of SwiftUI views.
- assumeIsolated(_:file:line:)
A safe way to synchronously assume that the current execution context belongs to the MainActor. This API should only be used as last resort, when it is not possible to express the current execution context definitely belongs to the main actor in other ways. E.g. one may need to use this in a delegate style API, where a synchronous method is guaranteed to be called by the main actor, however it is not possible to annotate this legacy API with @MainActor.
Warning: If the current executor is not the MainActor’s serial executor, this function will crash.
Note that this check is performed against the MainActor’s serial executor, meaning that if another actor uses the same serial executor–by using sharedUnownedExecutor as its own unownedExecutor–this check will succeed, as from a concurrency safety perspective, the serial executor guarantees mutual exclusion of those two actors.
- SwiftUIGPT
Expert in SwiftUI, SwiftData, and Observation framework
- Elixir Phoenix Researcher
Expert in Elixir and Phoenix, uses official docs and forums for answers.
- AsyncGraphics
AsyncGraphics is a Swift package for working with images and video with async / await. The core type is simply just called
Graphic
, it's like an image and is backed by aMTLTexture
. - AsyncStream.Continuation
A mechanism to interface between synchronous code and an asynchronous stream.
The closure you provide to the
AsyncStream
ininit(_:bufferingPolicy:\_:)
receives an instance of this type when invoked. Use this continuation to provide elements to the stream by calling one of theyield
methods, then terminate the stream normally by calling thefinish()
method.Note: Unlike other continuations in Swift, AsyncStream.Continuation supports escaping.
- Designing custom gestures in visionOS
To create a custom gesture, you rely on ARKit for information like hand positioning and joint orientation. Before you can offer custom gestures in your app, your app must be running in a Full Space and you must request people’s permission to access information about their hands. For developer guidance, see Setting up access to ARKit data.
Prioritize comfort in custom gestures. Continually test the ergonomics of all interactions that require custom gestures. A custom interaction that requires people to keep their arms raised for even a little while can be physically tiring, and repeating very similar movements many times in succession can stress people’s muscles and joints.
Consider carefully before defining custom gestures that involve multiple fingers or both hands. It can be challenging for people to perform custom gestures, and requiring them to position multiple fingers or use both hands at the same time can be even more difficult.
Avoid creating a custom gesture that requires people to use a specific hand. Expecting people to remember which hand to use for a custom gesture increases their cognitive load while also making your experience less welcoming to people with strong hand-dominance or limb differences.
If you decide to create a custom gesture, make sure it’s:
-
Inclusive. Gestures can mean different things to different people, so be sure your custom gestures don’t send messages you don’t intend.
-
Comfortable. Great custom gestures are physically easy for people to perform, especially over time.
-
Distinctive. Custom gestures that harmonize with your app or game can be easier for people to discover and remember, while enhancing their enjoyment of the experience.
-
Easy to describe. If you can’t use simple language and simple graphics to describe your custom gesture, it may mean that the gesture will be difficult for people to learn and perform.
-
- HandTrackingProvider
A source of live data about the position of a person’s hands and hand joints.
- Introducing Inferno: Metal shaders for SwiftUI
SwiftUI for iOS 17 and macOS Sonoma come with a fantastic new superpower: the ability to transform any SwiftUI view with Metal shaders, all hardware accelerated so complex effects run at lightning fast speeds even on old devices.
I want to help folks get started with Metal, so I've produced two free resources that will help everyone:
- Inferno is an open-source library of Metal shaders written for SwiftUI, giving you a range of powerful special effects in just a few lines of code.
- I released a new YouTube video where I walk through how to create Metal shaders for SwiftUI from scratch. It lasts over an hour, so there's lots of detail there.
Inferno is a project that makes Metal shaders easy for everyone to use, but I've also gone a step further and added comprehensive documentation explaining exactly how each shader works so that others can learn too.
- The complete guide to iOS & macOS development in Neovim
In this article, I will describe step by step how to configure Neovim to move away from Xcode. It took me several months to figure it all out piece by piece and to combine it into one working iOS development environment (I did it so you don’t have to :D). Hopefully, it won’t take you more than half a day to configure it with my help :).
It will be a little bit lengthy trip, and it will require setting up multiple plugins. I would recommend it to people who are already familiar with Vim. If you just installed Neovim, it could be overwhelming to learn Vim motions, Neovim environment, and set up dependencies, all at once.
If you are just starting with Neovim, take it slowly. First, learn Vim motions inside Xcode (by enabling Vim mode), in the meantime start configuring Neovim and get familiar with it by installing plugins, editing text files, JSON files, etc. Once you feel comfortable with Vim motions and Neovim, then try migrating your development :).
- RUN ANYTHING
pkgx
is a blazingly fast, standalone, cross‐platform binary that runs anything - values
The elements produced by the publisher, as an asynchronous sequence.
This property provides an AsyncPublisher, which allows you to use the Swift async-await syntax to receive the publisher’s elements. Because AsyncPublisher conforms to AsyncSequence, you iterate over its elements with a for-await-in loop, rather than attaching a subscriber.
The following example shows how to use the values property to receive elements asynchronously. The example adapts a code snippet from the filter(_:) operator’s documentation, which filters a sequence to only emit even integers. This example replaces the Subscribers.Sink subscriber with a for-await-in loop that iterates over the AsyncPublisher provided by the values property.
let numbers: [Int] = [1, 2, 3, 4, 5] let filtered = numbers.publisher .filter { $0 % 2 == 0 } for await number in filtered.values { print("\(number)", terminator: " ") }
- AsyncPublisher
A publisher that exposes its elements as an asynchronous sequence.
AsyncPublisher conforms to AsyncSequence, which allows callers to receive values with the for-await-in syntax, rather than attaching a Subscriber.
Use the values property of the Publisher protocol to wrap an existing publisher with an instance of this type.
- viewIsAppearing(_:)
Notifies the view controller that the system is adding the view controller’s view to a view hierarchy.
The system calls this method once each time a view controller’s view appears after the viewWillAppear(_:) call. In contrast to
viewWillAppear(_:)
, the system calls this method after it adds the view controller’s view to the view hierarchy, and the superview lays out the view controller’s view. By the time the system calls this method, both the view controller and its view have received updated trait collections and the view has accurate geometry.You can override this method to perform custom tasks associated with displaying the view. For example, you might use this method to configure or update views based on the trait collections of the view or view controller. Or, because computing a scroll position relies on the view’s size and geometry, you might programmatically scroll a collection or table view to ensure a selected cell is visible when the view appears.
If you override this method, you need to call super at some point in your implementation.
- Previews in Xcode
Generate dynamic, interactive previews of your custom views.
When you create a custom View with SwiftUI, Xcode can display a preview of the view’s content that stays up-to-date as you make changes to the view’s code. You use one of the preview macros — like Preview(_:body:) — to tell Xcode what to display. Xcode shows the preview in a canvas beside your code.
Different preview macros enable different kinds of configuration. For example, you can add traits that affect the preview’s appearance using the Preview(_:traits:_:body:) macro or add custom viewpoints for the preview using the Preview(_:traits:body:cameras:) macro. You can also check how your view behaves inside a specific scene type. For example, in visionOS you can use the Preview(_:immersionStyle:traits:body:) macro to preview your view inside an ImmersiveSpace. You typically rely on preview macros to create previews in your code. However, if you can’t get the behavior you need using a preview macro, you can use the PreviewProvider protocol and its associated supporting types to define and configure a preview.
- Immersive spaces
Display unbounded content in a person’s surroundings.
Use an immersive space to present SwiftUI views outside of any containers. You can include any views in a space, although you typically use a RealityView to present RealityKit content.
You can request one of three styles of spaces with the immersionStyle(selection:in:) scene modifier:
- The mixed style blends your content with passthrough. This enables you to place virtual objects in a person’s surroundings.
- The full style displays only your content, with passthrough turned off. This enables you to completely control the visual experience, like when you want to transport people to a new world.
- The progressive style completely replaces passthrough in a portion of the display. You might use this style to keep people grounded in the real world while displaying a view into another world.
When you open an immersive space, the system continues to display all of your app’s windows, but hides windows from other apps. The system supports displaying only one space at a time across all apps, so your app can only open a space if one isn’t already open.
- SpatialEventGesture
A gesture that provides information about ongoing spatial events like clicks and touches.
Use a gesture of this type to track multiple simultaneous spatial events and gain access to detailed information about each. For example, you can place a particle emitter at every location in a Canvas that has an ongoing spatial event:
struct ParticlePlayground: View { @State var model = ParticlesModel() var body: some View { Canvas { context, size in for particle in model.particles { context.fill(Path(ellipseIn: particle.frame), with: .color(particle.color)) } } .gesture( SpatialEventGesture() .onChanged { events in for event in events { if event.phase == .active { // Update particle emitters. model.emitters[event.id] = ParticlesModel.Emitter( location: event.location ) } else { // Remove emitters when no longer active. model.emitters[event.id] = nil } } } .onEnded { events in for event in events { // Remove emitters when no longer active. model.emitters[event.id] = nil } } ) } }
The gesture provides a SpatialEventCollection structure when it detects changes. The collection contains SpatialEventCollection.Event values that represent ongoing spatial events. Each event contains a stable, unique identifier so that you can track how the event changes over time. The event also indicates its current location, a timestamp, the pose of the input device that creates it, and other useful information.
The phase of events in the collection can change to SpatialEventCollection.Event.Phase.ended or SpatialEventCollection.Event.Phase.cancelled while the gesture itself remains active. Individually track state for each event inside onChanged(_:) or updating(_:body:) and clean up all state in onEnded(_:).
- Tim — Your iOS Mobile Dev Interview Coach
I help new and seasoned iOS developers do well on their take-home technical assessment, initial phone screen and on-site interviews. I can quiz you on system design whiteboarding, app architecture and common data structures & algorithms problems, based in Swift.
- ChatPRD
An on-demand Chief Product Officer that drafts and improves your PRDs, while coaching you to become an elite product manager.
- XcodeGPT
Your Xcode assistant with a new logo
- NSBundleResourceRequest
A resource manager you use to download content hosted on the App Store at the time your app needs it. You identify on-demand resources during development by creating string identifiers known as tags and assigning one or more tags to each resource. An
NSBundleResourceRequest
object manages the resources marked by one or more tags.You use the resource request to inform the system when the managed tags are needed and when you have finished accessing them. The resource request manages the downloading of any resources marked with the managed tags that are not already on the device and informs your app when the resources are ready for use.
The system will not attempt to purge the resources marked with a tag from on-device storage as long as at least one NSBundleResourceRequest object is managing the tag. Apps can access resources after the completion handler of either beginAccessingResources(completionHandler:) or conditionallyBeginAccessingResources(completionHandler:) is called successfully. Management ends after a call to endAccessingResources() or after the resource request object is deallocated.
Other properties and methods let you track the progress of a download, change the priority of a download, and check whether the resources marked by a set of tags are already on the device. Methods in Bundle indicate to the system the relative importance of preserving a tag in memory after it is no longer in use. For more information, see setPreservationPriority(_:forTags:) and preservationPriority(forTag:).
- XcodeGPT
XcodeGPT is your go-to assistant for any queries about Xcode, its build systems, and project management. This model is not only trained with publicly available Xcode data but also infused with the nuanced understanding we have developed over the years. We are committed to continually updating XcodeGPT with our latest insights, ensuring it remains an invaluable resource for the most current Xcode information.
Experience XcodeGPT in action here.
- Adopting the system player interface in visionOS
Provide an optimized viewing experience for watching 3D video content.
The recommended way to provide a video playback interface for your visionOS app is to adopt AVPlayerViewController. Using this class makes it simple to provide the same playback user interface and features found in system apps like TV and Music. It also provides essential system integration to deliver an optimal viewing experience whether you’re playing standard 2D content or immersive 3D video with spatial audio. This article describes best practices for presenting the player in visionOS and covers the options the player provides to customize its user interface to best fit your app.
- Positioning and sizing windows
Influence the initial geometry of windows that your app presents.
visionOS and macOS enable people to move and resize windows. In some cases, your app can use scene modifiers to influence a window’s initial geometry on these platforms, as well as to specify the strategy that the system employs to place minimum and maximum size limitations on a window. This kind of configuration affects both windows and volumes, which are windows with the volumetric window style.
Your ability to configure window size and position is subject to the following constraints:
- The system might be unable to fulfill your request. For example, if you specify a default size that’s outside the range of the window’s resizability, the system clamps the affected dimension to keep it in range.
- Although you can change the window’s content, you can’t directly manipulate window position or size after the window appears. This ensures that people have full control over their workspace.
- During state restoration, the system restores windows to their previous position and size.
- GeometryReader: Blessing or Curse?
GeometryReader has been present since the birth of SwiftUI, playing a crucial role in many scenarios. However, from the very beginning, some developers have held a negative attitude towards it, believing it should be avoided as much as possible. Especially after the recent updates of SwiftUI added some APIs that can replace GeometryReader, this view has further strengthened.
This article will dissect the “common problems” of GeometryReader to see if it is really so unbearable, and whether those performances criticized as “not meeting expectations” are actually due to problems with the developers’ “expectations” themselves.
- Swiftie
An expert Swift developer at your service*
*Requires ChatGPT Plus
- Reasync.swift
extension Result where Failure == Swift.Error {
/// Creates a new result by evaluating an async throwing closure, capturing the returned value as
/// a success, or any thrown error as a failure.
///
/// - Parameter body: A throwing closure to evaluate.
@_transparent
public init(catching body: () async throws -> Success) async {
do {
self = .success(try await body())
} catch {
self = .failure(error)
}
}
}
@_transparent
Semantically,
@_transparent
means something like "treat this operation as if it were a primitive operation". The name is meant to imply that both the compiler and the compiled program will "see through" the operation to its implementation.This has several consequences:
- Any calls to a function marked
@_transparent
MUST be inlined prior to doing dataflow-related diagnostics, even under-Onone
. This may be necessary to catch dataflow errors. - Because of this, a
@_transparent
function is implicitly inlinable, in that changing its implementation most likely will not affect callers in existing compiled binaries. - Because of this, a public or
@usableFromInline
@_transparent
function MUST only reference public symbols, and MUST not be optimized based on knowledge of the module it's in. [The former is caught by checks in Sema.] - Debug info SHOULD skip over the inlined operations when single-stepping through the calling function.
This is all that
@_transparent
means.- Any calls to a function marked
- Fucking Format Style!
Format Styles In Excruciating Detail
Swift’s
FormatStyle
andParseableFormatStyle
are the easiest way to convert Foundation data types to and from localized strings. Unfortunately Apple hasn’t done a great job in documenting just what it can do, or how to use them. - Integrating Swift Macros with Xcodeproj native blocks
Swift Macros were introduced by Apple as a feature bundled within Swift Packages. This approach enhances shareability—a notable limitation of XcodeProj elements like targets. However, it also tightens the reliance on seamless integration between Xcode and the Swift Package Manager (SPM), which, from my experience and that of others, can be less than ideal in large projects with numerous dependencies. In fact, some developers are shifting towards Tuist’s methodology, reminiscent of CocoaPods, where projects are immediately ready for compilation upon opening.
Given the suboptimal experience offered by Apple’s ecosystem, which precludes optimization opportunities, Tuist employs SPM to resolve packages before mapping them onto Xcodeproj elements. While generally effective, this approach has encountered occasional setbacks, which developers can rectify by tweaking the build settings of the generated targets. Yet, it has not supported Swift Macros since their announcement.
Interestingly, developers managing Xcode rules for Bazel quickly devised a method to accommodate Swift Macros using compiler flags. Inspired by this, could Tuist adopt a similar strategy by utilizing targets, dependencies, and build settings? After some investigation, the answer is affirmative. Here’s the blueprint:
The macro’s representative target must be a macOS command-line target, encompassing the macro’s source code. A secondary, dependent target is required, hosting the public macro definition for import by other targets.
Targets wishing to leverage the macro should:
- Establish a dependency on the secondary target for prior compilation.
- Include the setting
OTHER_SWIFT_FLAGS
with the value-load-plugin-executable $BUILT_PRODUCTS_DIR/ExecutableName\#ExecutableName.
This setup is contingent upon the secondary target and the dependent targets producing their outputs in the same directory. If that’s not the case,
SWIFT_INCLUDE_PATHS
will be necessary to make the module available to the dependent targets. - On-Crash Backtraces in Swift
The new Swift 5.9 release contains a number of helpful, new features for debugging code, including an out-of-process, interactive crash handler to inspect crashes in real time, the ability to trigger the debugger for just-in-time debugging, along with concurrency-aware backtracing to make it easier to understand control flow in a program that uses structured concurrency.
- Automerge-Repo: A "batteries-included" toolkit for building local-first applications
Today we are announcing our new library,
automerge-repo
, which makes it vastly easier to build local-first applications with Automerge. Take a look at our quickstart guide or read on for some background and examples.For those new to this idea: local-first applications are a way of building software that allows both real-time collaboration (think Google Docs) and offline working (think Git). They work by storing the user's data locally, on their own device, and syncing it with collaborators in the background. You can read more about the motivation for local-first software in our essay, or watch a talk introducing the idea.
A challenge in local-first software is how to merge edits that were made independently on different devices, and CRDTs were developed to solve this problem. Automerge is a fairly mature CRDT implementation. In fact, we wrote this blog post using it! The API is quite low-level though, and Automerge-Core has no opinion about how networking or storage should be done. Often, the first thing developers ask after discovering Automerge was how to connect it into an actual application.
Our new library,
automerge-repo
, extends the collaboration engine of Automerge-Core with networking and storage adapters, and provides integrations with React and other UI frameworks. You can get to building your app straight away by taking advantage of default implementations that solve common problems such as how to send binary data over a WebSocket, how often to send synchronization messages, what network format to use, or how to store data in places like the browser's IndexedDB or on the filesystem. - Functional event sourcing example in Kotlin
We explained the implementation details of an event-sourced functional domain model in Kotlin. In the process, we attempted to show how straightforward testing of such a model can be and how it doesn't require any dedicated testing techniques or tools. The model itself, on the other hand, remains a rich core of business logic.
- Layout Guidelines
The following sections are general guidelines that describe fundamental Mac layout principles of center equalization, text and control alignment, appropriate use of white space, and visual balance. Following these guidelines will help you create functional and aesthetically pleasing windows that are easy for Mac users to understand and use.
As you layout your window, remember to observe the principle of consistency in your decisions. If you have good reasons to break some layout guidelines, be sure to do it in a consistent way. Users tend to ignore symmetry and balance but will notice inconsistency.
Inconsistencies in a window can also lead users to conclude that the window was poorly designed and/or implemented. For example, users won’t notice if the margins inside your window edges are 18 points wide (instead of the recommended 20 points), but are likely to notice if the left margin is wider than the right one.
isNewline
A Boolean value indicating whether this character represents a newline.
- TN3135: Low-level networking on watchOS
Learn about the supported use cases for low-level networking on watchOS.
watchOS groups networking into two categories:
- High-level networking. This includes the HTTP and HTTPS support in URLSession, and any code layered on top of that.
- Low-level networking. This includes Network framework, NSStream, and any other API that runs a TCP connection or UDP session directly. That includes the low-level aspects of URLSession, namely URLSessionStreamTask and URLSessionWebSocketTask. It also includes APIs, like NWBrowser and NSNetService, that interact directly with Bonjour.
watchOS allows all apps to use high-level networking equally. However, it only allows an app to use low-level networking under specific circumstances:
- It allows an audio streaming app to use low-level networking while actively streaming audio. Support for this was introduced in watchOS 6.
- It allows a VoIP app to use low-level networking while running a call using CallKit. Support for this was added in watchOS 9.
- It allows an app on watchOS to set up an application service listener so that the same app on tvOS can establish a low-level connection to it using the DeviceDiscoveryUI framework. Support for this was added in watchOS 9 and tvOS 16.
- Bonjour
Bonjour, also known as zero-configuration networking, enables automatic discovery of devices and services on a local network using industry standard IP protocols. Bonjour makes it easy to discover, publish, and resolve network services with a sophisticated, easy-to-use programming interface that is accessible from Cocoa, Ruby, Python, and other languages.
- Use Visual Look Up to identify objects in your photos and videos on iPhone
With Visual Look Up, you can identify and learn about popular landmarks, plants, pets, and more that appear in your photos and videos in the Photos app . Visual Look Up can also identify food in a photo and suggest related recipes.
- Hierarchical background styles in SwiftUI
Starting from iOS 17 we now have new properties, such as secondary, tertiary, quaternary and quinary that are defined on an instance of a
ShapeStyle
. To get hierarchical background colors we simply have to access these properties on the current background style:BackgroundStyle().secondary
.BackgroundStyle
in SwiftUI conforms toShapeStyle
protocol, so accessing thesecondary
property on an instance of aBackgroundStyle
will return the second level of the background in the current context that depends on the operating system and color scheme (light or dark mode enabled).We can also get the current background style from the static
background
property defined onShapeStyle
. - macOS Containers
Containers have fundamentally changed the way that modern software is developed and deployed. Containers are supported by a wide range of operating systems including FreeBSD, Solaris, Linux and even Windows, but are not natively supported by macOS. Until now.
- Incorporating real-world surroundings in an immersive experience
Create an immersive experience by making your app’s content respond to the local shape of the world.
- Orion
Finally, a display that can go with you anywhere.
Orion turns iPad into your portable HDMI Monitor.
- New Computer
Dot by New Computer is an intelligent guide designed to help you remember, organize, and navigate your life.
- Swift Packages
The Swift package ecosystem has thousands of packages to help you with all kinds of tasks across your projects. You’ll find networking, testing, UI helpers, logging, animation, and many more packages that work with the Swift Package Manager (SwiftPM).
- More Data Types with Negation at Fun in the REPL
The gist of the talk is: what if we could define a predicate for even numbers like this in Agda (or Coq or Idris or Lean):
data Even : Nat → Set where zero : Even 0 suc : ∀ {n} → not (Even n) → Even (suc n)
So
0
is even, andsuc n
is even ifn
isn't.But if we get this to work, then what would this declaration mean?
data Liar : Set where liar : not Liar → Liar
- Misty Programming Language
The Misty Programming Language is a dynamic, general-purpose, transitional, actor language. It has a gentle syntax that is intended to benefit students, as well as advanced features such as capability security and lambdas with lexical scoping.
The grammar of the language is expressed in McKeeman Form.
- Machine learning of GUIs at scale
Imagine if you could say to ChatGPT, "Go try out my app for 5 minutes and let me know what you think about the getting started experience." Or if you could ask questions like... Does my iOS app's GUI follow common practices? Is it accessible? What are some examples of apps that use these specific UI controls on the same screen?
If we had a rich database of app GUIs and the right ML models, then we could answer these questions and build a copilot tool that "understands" the visual and interaction designs of GUIs, not just the code!
- GitHub Tip: using the involves filter
However, wouldn’t it also be nice to see all of these pull requests at once? That is, all of your own pull requests, everything assigned to review, and everything where you are actively in discussion? You can, with the filter
involves:@me
, which will show you all the pull requests you are involved in, in any capacity. In other words, it shows you everything that requires your attention. - Swift, meet WinRT
Open sourcing our Swift bindings generator for WinRT — and an end-to-end sample application for anyone looking to build a modern Windows application in Swift.
- Through the Ages: Apple CPU Architecture
Learn how CPUs work, and discover Apple’s underrated competitive advantage.
- Build SwiftUI apps for iOS and Android with Skip
Skip is your automated Android development partner. As you develop your modern Swift and SwiftUI iOS app, Skip's intelligent transpiler generates the equivalent Kotlin and Compose Android app alongside it. Deliver fully native apps for both the App Store and Play Store with one team, one language, and one codebase.
Want to learn more? Take our video tour or browse the documentation.
- Figma Event Storming template
Break down software development programs into a self-explanatory sequence or hash out the steps involved in getting your startup off the ground. An event storming session enlightens the whole team.
- Deploying Transformers on the Apple Neural Engine
An increasing number of the machine learning (ML) models we build at Apple each year are either partly or fully adopting the Transformer architecture. This architecture helps enable experiences such as panoptic segmentation in Camera with HyperDETR, on-device scene analysis in Photos, image captioning for accessibility, machine translation, and many others. This year at WWDC 2022, Apple is making available an open-source reference PyTorch implementation of the Transformer architecture, giving developers worldwide a way to seamlessly deploy their state-of-the-art Transformer models on Apple devices.
This implementation is specifically optimized for the Apple Neural Engine (ANE), the energy-efficient and high-throughput engine for ML inference on Apple silicon. It will help developers minimize the impact of their ML inference workloads on app memory, app responsiveness, and device battery life. Increasing the adoption of on-device ML deployment will also benefit user privacy, since data for inference workloads remains on-device, not on the server.
In this article we share the principles behind this reference implementation to provide generalizable guidance to developers on optimizing their models for ANE execution. Then, we put these principles into action and showcase how to deploy an example pretrained Transformer model, the popular Hugging Face distilbert, in just a few lines of code. Notably, this model, which works out-of-the-box and on device using Core ML already, is up to 10 times faster and consumes 14 times less memory after our optimizations.
- Create your own custom skins with a text prompt!
SkinGenerator.io uses custom generative art models to generate skins for video games. With a simple text prompt you can create characters quickly and easily. You're limited only by your imagination!
- SwiftUI Sheet never releases object from memory on iOS 17
I've found a very strange behaviour which looks like a bug. SwiftUI sheet or fullScreenCover do not release objects that were passed to its item: parameter (and to the view builder body by the way, but here is the simplified case).
It works well and memory is releasing on iOS 16 built with both Xcode 14 or 15. (simulators, devices)
Memory is leaking and NOT releasing on iOS 17 built with Xcode 15. (simulator, device 17.0.2)
- iLeakage: Browser-based Timerless Speculative Execution Attacks on Apple Devices
We present iLeakage, a transient execution side channel targeting the Safari web browser present on Macs, iPads and iPhones. iLeakage shows that the Spectre attack is still relevant and exploitable, even after nearly 6 years of effort to mitigate it since its discovery. We show how an attacker can induce Safari to render an arbitrary webpage, subsequently recovering sensitive information present within it using speculative execution. In particular, we demonstrate how Safari allows a malicious webpage to recover secrets from popular high-value targets, such as Gmail inbox content. Finally, we demonstrate the recovery of passwords, in case these are autofilled by credential managers.
- RealityKit
Simulate and render 3D content for use in your augmented reality apps.
RealityKit provides high-performance 3D simulation and rendering capabilities you can use to create visionOS apps or to create augmented reality (AR) apps for iOS, macOS, and tvOS. RealityKit is an AR-first 3D framework that leverages ARKit to seamlessly integrate virtual objects into the real world.
Use RealityKit’s rich functionality to create compelling augmented reality (AR) experiences.
- Create and import full RealityKit scenes with models, animations, and Spatial Audio by using Reality Composer Pro for visionOS.
- Build or modify scenes at runtime by adding 3D models, shape primitives, and sounds from code.
- Have virtual objects interact with objects in the real-world.
- Animate objects, both manually and with physics simulations.
- Respond to user input and changes in a person’s surroundings.
- Synchronize across devices and use SharePlay to enable group AR experiences.
- Understanding RealityKit’s modular architecture
Learn how everything fits together in RealityKit.
RealityKit is a 3D framework designed for building apps, games, and other immersive experiences. Although it’s built in an object-oriented language and uses object-oriented design principles, RealityKit’s architecture avoids heavy use of composition — where objects are built by adding instance variables that hold references to other objects — in favor of a modular design based on a paradigm called Entity Component System (ECS) that divides application objects into one of three types.
Following the ECS paradigm allows you to re-use the functionality contained in a component in many different entities, even if they have very different inheritance chains. Even if two objects have no common ancestors other than Entity, you can add the same components to both of them and give them the same behavior or functionality.
- Spatial layout
Spatial layout techniques help you take advantage of the infinite canvas of Apple Vision Pro and present your content in engaging, comfortable ways.
- Immersive experiences
In visionOS, you can design apps and games that extend beyond windows and volumes, and let people immerse themselves in your content.
In visionOS, people can run multiple apps at the same time in the Shared Space or concentrate on a single app at a time in a Full Space. By default, your app launches in the Shared Space, where people can switch between multiple running apps much as they do on a Mac. When they want a more immersive experience, people can transition your app to a Full Space, where other apps hide and your app can display content anywhere.
- HTTP Live Streaming Examples
View various examples of .M3U8 files formatted to index streams and .ts media segment files on your Mac, iPhone, iPad, and Apple TV.
- Ducklet for SQLite
The fast, native SQLite database editor for macOS.
- Spatial
Create and manipulate 3D mathematical primitives.
The Spatial module is a lightweight 3D mathematical library that provides a simple API for working with 3D primitives. Much of its functionality is similar to the 2D geometry support in Core Graphics, but in three dimensions.
- Swift concurrency: Behind the scenes (2021)
Dive into the details of Swift concurrency and discover how Swift provides greater safety from data races and thread explosion while simultaneously improving performance. We'll explore how Swift tasks differ from Grand Central Dispatch, how the new cooperative threading model works, and how to ensure the best performance for your apps. To get the most out of this session, we recommend first watching “Meet async/await in Swift,” “Explore structured concurrency in Swift,” and “Protect mutable state with Swift actors.”
- VideoPlayerComponent
In visionOS, the
VideoPlayerComponent
is another way to create a video scene (including for HEVC video with transparency). - Designing for visionOS
When people wear Apple Vision Pro, they enter an infinite 3D space where they can engage with your app or game while staying connected to their surroundings.
- Playing video — visionOS
Help people stay comfortable when playing video in your app. Often, an app doesn’t control the content in the videos it plays, but you can help people stay comfortable by:
- Letting them choose when to start playing a video
- Using a small window for playback, letting people resize it if they want
- Making sure people can see their surroundings during playback
In a fully immersive experience, avoid letting virtual content obscure playback or transport controls. In a fully immersive context, the system automatically places the video player at a predictable location that provides an optimal viewing experience. Use this location to help make sure that no virtual content occludes the default playback or transport controls in the ornament near the bottom of the player.
Avoid automatically starting a fully immersive video playback experience. People need control over their experience and they’re unlikely to appreciate being launched into a fully immersive video without warning.
Create a thumbnail track if you want to support scrubbing. The system displays thumbnails as people scrub to different times in the video, helping them choose the section they want. To improve performance, supply a set of thumbnails that each measure 160 px in width. For developer guidance, see HTTP Live Streaming (HLS) Authoring Specification for Apple Devices > Trick Play.
Avoid expanding an inline video player to fill a window. When you display the system-provided player view in a window, playback controls appear in the same plane as the player view and not in an ornament that floats above the window. Inline video needs to be 2D and you want to make sure that window content remains visible around the player so people don’t expect a more immersive playback experience. For developer guidance, see AVPlayerViewController.
Use a RealityKit video player if you need to play video in a view like a splash screen or a transitional view. In situations like these, people generally expect the video to lead into the next experience, so they don’t need playback controls or system-provided integration, like dimming and view anchoring. The RealityKit video player automatically uses the correct aspect ratio for both 2D and 3D video and supports closed captions. RealityKit can also help you play video as a special effect on the surface of a custom view or object. For developer guidance, see RealityKit.
- Playing audio — visionOS
Subtle, expressive sounds are everywhere in visionOS, enhancing experiences and providing essential feedback when people look at a virtual object and use gestures to interact with it. The system combines audio algorithms with information about a person’s physical surroundings to produce Spatial Audio, which is sound that people can perceive as coming from specific locations in space, not just from speakers.
In visionOS, audio playback from the Now Playing app pauses automatically when people close the app’s window, and audio from an app that isn’t the Now Playing app can duck when people look away from it to different app.
Prefer playing sound. People generally choose to keep sounds audible while they’re wearing the device, so an app that doesn’t play sound — especially in an immersive moment — can feel lifeless and may even seem broken. Throughout the design process, look for opportunities to create meaningful sounds that aid navigation and help people understand the spatial qualities of your app.
Design custom sounds for custom UI elements. In general, a system-provided element plays sound to help people locate it and receive feedback when they interact with it. To help people interact with your custom elements, design sounds that provide feedback and enhance the spatial experience of your app.
Use Spatial Audio to create an intuitive, engaging experience. Because people can perceive Spatial Audio as coming from anywhere around them, it works especially well in a fully immersive context as a way to help an experience feel lifelike. Ambient audio provides pervasive sounds that can help anchor people in a virtual world and an audio source can sound like it comes from a specific object. As you build the soundscape for your app, consider using both types of audio.
Consider defining a range of places from which your app sounds can originate. Spatial Audio helps people locate the object that’s making sound, whether it’s stationary or moving in space. For example, when people move an app window that’s playing audio, the sound continues to come directly from the window, wherever people move it.
Consider varying sounds that people could perceive as repetitive over time. For example, the system subtly varies the pitch and volume of the virtual keyboard’s sounds, suggesting the different sounds a physical keyboard can make as people naturally vary the speed and forcefulness of their typing. An efficient way to achieve a pleasing variation in sound is to randomize a sound file’s pitch and volume during playback, instead of creating different files.
Decide whether you need to play sound that’s fixed to the wearer or tracked by the wearer. People perceive fixed sound as if it’s pointed at them, regardless of the direction they look or the virtual objects they move. In contrast, people tend to perceive tracked sound as coming from a particular object, so moving the object closer or farther away changes what they hear. In general, you want to use tracked sound to enhance the realism of your experience, but there could be cases where fixed sound is a good choice. For example, Mindfulness uses fixed sound to envelop the wearer in an engaging, peaceful setting.
- Mountain Town Technology!
Welcome to the future of media production
The creator economy will always struggle so long as the tooling is controlled by some massive body that can set the terms of creation. The solution is to make the tools cheap enough to scale and accessible to the point where they’re table stakes.
- Creating a game with scene understanding
Create AR games and experiences that interact with real-world objects on LiDAR-equipped iOS devices.
- Deploy and manage Apple hardware, software, and services in your organization
Apple devices integrate hardware, software, apps, and services to let you manage your deployment projects easily. Get the control and flexibility you want by using Apple School Manager or Apple Business Manager and your chosen mobile device management solution.
- Introducing Insights, and new pricing
The Reveal team have spent more than a year building the new Insights workspace, working with industry experts and organisations to encode their expertise into more than 130 rules that pinpoint areas of improvement for your app. These rules are based on a combination of industry and platform-specific guidelines, best practices and over a decade of our own experience developing apps.
Insights runs a powerful, accessibility-focused audit of your app using information extracted from both the visual and accessible user interfaces of your app. This combination of the accessible and visual user interfaces is unique to Reveal, and allows us to provide a level of insight that is more powerful than anything else available for iOS, iPadOS and tvOS.
This new functionality takes Reveal from a passive developer tool, where you need to know what to look for in order to identify issues, to one that proactively surfaces problems along with suggestions on how to fix them. This radically improves developer efficiency and allows you to see and address issues you may never have know existed in your apps.
- Controlled installation of Lean 4 on MacOS
This document explains a more controlled installation procedure for Lean on MacOS. There is a quicker way described in the main install page but it requires more trust.
- Destination Video
Leverage 3D video and Spatial Audio to deliver an immersive experience.
Destination Video is a multiplatform video-playback app for visionOS, iOS, and tvOS. People get a familiar media-browsing experience navigating the libraryʼs content and playing videos they find interesting. The app provides a similar experience on supported platforms, but leverages unique features of visionOS to create a novel, immersive playback experience.
- Designing RealityKit content with Reality Composer Pro
Design RealityKit scenes for your visionOS app.
Use Reality Composer Pro to visually design, edit, and preview RealityKit content. In Reality Composer Pro, you can create one or more scenes, which act as a container for RealityKit content. Scenes contain hierarchies of entities, which are virtual objects such as 3D models.
- VideoMaterial
A material that supports animated textures.
In RealityKit, a material is an object that defines the surface properties of a rendered 3D object. A
VideoMaterial
is a material that maps a movie file on to the surface of an entity. Video materials are unlit, which means that scene lighting doesn’t affect them. Video materials support transparency if the source video’s file format also supports transparency.Video materials use an AVPlayer instance to control movie playback. You can use any movie file format that AVPlayer supports to create a video material. To control playback of the material’s video, use the avPlayer property, which offers methods like play() and pause().
The following code demonstrates how to create and start playing a video material using a movie file from your application bundle.
- Managing custom properties for repositories in your organization
With custom properties, you can add metadata to repositories in your organization. You can use those properties to target repositories with rulesets.
- Geometry to Algebra and Back Again — 4000 Years of Papers
This is going to be an unusual Papers We Love talk, as I'm going to discuss a bunch of different papers in relatively light detail but with rich historical context. I'll post a transcript and mini-site for this talk that has links to all these papers, and many others that serve as supporting material.
Last year, I gave a talk at Strange Loop where I said everyone is programming wrong. This upset some people, so I thought I'd make a more modest claim today: Everyone is doing mathematics wrong
- Apparency
The App That Opens Apps
WHAT HAPPENS WHEN YOU OPEN THAT APP?
macOS checks every app against a slew of security features: Gatekeeper, notarization, hardening, entitlements and more. But it doesn't show you the result of these checks, preferring to keep these behind the scenes — either the app opens or it doesn't, perhaps with an “app downloaded from the internet” dialog first.
Even “code signatures” — around since Mac OS X 10.5 (Leopard!) — are visible only via arcane Terminal incantations.
WHAT'S INSIDE THAT APP?
Today's macOS apps are often made up of many pieces. Some of these are organizational artifacts, of interest only to the developers.
But some pieces of an app can extend macOS itself — Share Extensions, Today Widgets, Safari Extensions, Quick Look generators, Spotlight importers, and so on. macOS lets you see and manage some of these, but not all of them, and not all in one place.
ENTER APPARENCY — THE APP THAT OPENS APPS.
Control-click on an app in the Finder, choose Open With Apparency, and see all the details in one place
- MLC LLM iOS app and Swift API
The MLC LLM iOS app can be installed in two ways: through the pre-built package or by building from source. If you are an iOS user looking to try out the models, the pre-built package is recommended. If you are a developer seeking to integrate new features into the package, building the iOS package from source is required.
- Galaxy of Horrors
Take a tour of some of the most terrifying and mind-blowing destinations in our galaxy ... and beyond. After a visit to these nightmare worlds, you may never want to leave Earth again! You can also download our free posters — based on real NASA science — if you dare.
- isiOSAppOnMac
A Boolean value that indicates whether the process is an iPhone or iPad app running on a Mac.
The value of this property is
true
only when the process is an iOS app running on a Mac. The value of the property isfalse
for all other apps on the Mac, including Mac apps built using Mac Catalyst. The property is alsofalse
for processes running on platforms other than macOS. - EffectsLibrary tutorials
This is a library for creating full screen effects in SwiftUI in an easy, seamless way. The package is available on Swift Package Manager (SPM) and fully open-source.
- Using SwiftTreeSitter
SwiftTreeSitter provides a Swift interface to the tree-sitter incremental parsing system. You can use it to parse language text, reparse it as it changes, and query the syntax tree.
- SwiftFormat Automation for iOS apps
In this article, I'll go through various options to implement SwiftFormat on a production project rather than how to integrate the tool locally (this is relatively straightforward). This is because I believe the tool provides greater benefit as an automation for every developer on the team, rather than a few only. We'll also cover the relative advantages or disadvantages. I hope that this will help you choose the right tool for your project.
- Swift Splash
Use RealityKit to create an interactive ride in visionOS.
Swift Splash uses multiple Reality Composer Scenes to create prepackaged entity hierarchies that represent each of the slide pieces the player connects to construct their ride. It demonstrates how to hide and reveal sections of the entity hierarchy based on the current state of the app. For example, each slide piece contains an animated fish entity that’s hidden until the ride runs and the fish arrives at that particular piece. While Swift Splash is a fun, game-like experience, the core idea of assembling virtual objects out of predefined parts can also be used as the basis for a productivity or creation app.
- Tart
Tart is a virtualization toolset to build, run and manage macOS and Linux virtual machines on Apple Silicon.
- Pijul
A sound and fast distributed version control system based on a mathematical theory of asynchronous work.
- Conditional Xcode Build Settings
There’s no straightforward way to avoid this problem, but Xcode build settings offer a sophisticated (albeit brain-bendingly obtuse) mechanism for varying the value of a build setting based on arbitrary conditions. Technically this technique could be used in Xcode’s build settings editor, but because of the complexity of variable definitions, it’s a lot easier (not to mention easier to manage with source control) if you declare such settings in an Xcode configuration file. The examples below will use the declarative format used by these files.
The key to applying this technique is understanding that build settings can themselves be defined in terms of other build settings.
- Choose Boring Technology
This is the spoken word version of my essay, Choose Boring Technology. I have largely come to terms with it and the reality that I will never escape its popularity.
I gave this most recently at the WikiMedia Foundation’s developer conference, where Scott Ananian called it “how to be old, for young people.” Here are my other talks, my website, and some Medium posts.
- PROJEKT: OVERFLOW — RISC-V assembly board game
I made this game to teach my daughter how buffer overflows work. Looking at programs as something you can play with, and poke and twist and make it do something else, is my favourite part of modern computing. I think its the right way to look at programs. When your microwave oven gets an update and starts crashing, you can hack it. Or when your keyboard controller’s firmware is bad, you can hack it (looking at you vortex pok3r). She is 12 yo now but her assembler skills are getting better and better, hopefully one day she will be able to hack her own keyboard :)
The game is about creating a small shellcode in memory by copying existing instructions and then exploiting a buffer overflow to jump into it, so that you can overwrite your opponent’s return address to force them to go to the game_over() function.There are other mechanics as well and more layers of strategy (like setting the exception handler or monkeypatching).
All players share the same memory, and execute the same program, while time sharing the same processor running preemptive scheduling os, so each turn the player executes 10 instructions, after that the process is interrupted by the operating system, and its the other player's turn. Each player's stack pointer starts at a different location. There is no virtual memory.
- Debugging Improvements in Swift 5.9
Faster variable inspection with
p
andpo
LLDB provides the shorthand
p
command alias to inspect variables and po to call the debugDescription property of objects. Originally, these were aliases for the rather heavyweightexpression
andexpression -O
commands. In Swift 5.9, thep
andpo
command aliases have been redefined to the new dwim-print command.The
dwim-print
command prints values using the most user-friendly implementation. “DWIM” is an acronym for “Do What I Mean”. Specifically, when printing variables,dwim-print
will use the same implementation asframe variable
orv
instead of the more expensive expression evaluator.In addition to being faster, using
p
no longer creates persistent result variables like$R0
, which are often unused in debugging sessions. Persistent result variables not only incur overhead but also retain any objects they contain, which can be an unexpected side effect for the program execution. Support for generic type parameters in expressionsLLDB now supports referring to generic type parameters in expression evaluation. For example, given the following code:
func use<T>(_ t: T) { print(t) // break here } use(5) use("Hello!")
Running
po T.self
, when stopped in use, will printInt
when coming in through the first call, andString
in the second.Fine-grained scope information
The Swift compiler now emits more precise lexical scopes in debug information, allowing the debugger to better distinguish between different variables, like the many variables named x in the following example:
func f(x: AnyObject?) { // function parameter `x: AnyObject?` guard let x else {} // local variable `x: AnyObject`, which shadows the function argument `x` ... }
In Swift 5.9, the compiler now uses more accurate
ASTScope
information to generate the lexical scope hierarchy in the debug information, which results in some behavior changes in the debugger. - Twitter Network Layer (a.k.a TNL)
The Twitter Network Layer (TNL) is a framework for interfacing with the Apple provided
NSURLSession
stack that provides additional levels of control and insight over networking requests, provides simple configurability and minimizes the cognitive load necessary to maintain a robust and wide-reaching networking system. - Interacting with your app in the visionOS simulator
To use your Mac’s pointer and keyboard to create gestures, choose “Select to interact with the scene” from the buttons at the bottom-right of a visionOS simulator window. The current gaze position tracks your pointer movements when you hover over content within the space.
Use the following actions to trigger gestures:
Gesture To simulate Tap Click. Double-tap Double-click. Touch and hold Click and hold. Drag (left, right, up, and down) Drag left, right, up, and down. Drag (forward and back) Shift-drag up and down. Two-handed gestures Press and hold the Option key to display touch points. Move the pointer while pressing the Option key to change the distance between the touch points. Move the pointer and hold the Shift and Option keys to reposition the touch points. Activate device buttons using menu items or by clicking the controls in the simulator window toolbar.
Use your Mac’s pointer and the keyboard to reposition your viewpoint in a visionOS simulator window:
Movement To simulate Forward Press the W key (or Up Arrow key), or perform a pinch gesture moving two fingers away from each other on a trackpad. Backward Press the S key (or Down Arrow key), or perform a pinch gesture moving two fingers toward each other on a trackpad. Left Press the A key (or Left Arrow key), or scroll left using a trackpad or Magic Mouse. Right Press the D key (or Right Arrow key), or scroll right using a trackpad or Magic Mouse. Up Press the E key, or scroll up using a trackpad or Magic Mouse. Down Press the Q key, or scroll down using a trackpad or Magic Mouse. - Understanding RealityKit’s modular architecture
RealityKit is a 3D framework designed for building apps, games, and other immersive experiences. Although it’s built in an object-oriented language and uses object-oriented design principles, RealityKit’s architecture avoids heavy use of composition — where objects are built by adding instance variables that hold references to other objects — in favor of a modular design based on a paradigm called Entity Component System (ECS) that divides application objects into one of three types.
Following the ECS paradigm allows you to re-use the functionality contained in a component in many different entities, even if they have very different inheritance chains. Even if two objects have no common ancestors other than Entity, you can add the same components to both of them and give them the same behavior or functionality.
- Bezel
Show your iPhone on your Mac
Bezel is the easiest way to view, present and record an iPhone.
- Prompt engineering for Claude's long context window
Claude’s 100,000 token long context window enables the model to operate over hundreds of pages of technical documentation, or even an entire book. As we continue to scale the Claude API, we’re seeing increased demand for prompting guidance on how to maximize Claude’s potential. Today, we’re pleased to share a quantitative case study on two techniques that can improve Claude’s recall over long contexts:
- Extracting reference quotes relevant to the question before answering
- Supplementing the prompt with examples of correctly answered questions about other sections of the document
- A New API Direction for Testing in Swift
A key requirement for the success of any developer platform is a way to use automated testing to identify software defects. Better APIs and tools for testing can greatly improve a platform’s quality. Below, we propose a new API direction for testing in Swift.
We start by defining our basic principles and describe specific features that embody those principles. We then discuss several design considerations in-depth. Finally, we present specific ideas for delivering an all-new testing API in Swift, and weigh them against alternatives considered.
- Why not React?
This analysis is harsh on React’s MPA suitability. But is that so odd?
It was created to client-render non-core bits of Facebook. Its maintainers only recently used it for server rendering, navigation, or delivering traditional web content. In fact, its SSR was a happy accident. And finally, longstanding evidence holds React trends antagonistic towards performance.
Why would React be good at the things we ask it to do?
With the FB5 redesign, Facebook is finally using React in the ways that we are, and they have found it wanting. On the one hand, this means React will surely become much better at desirable SSR features. On the other, when this will happen is unsure, it will heavily change React’s roadmap, and React could change so much that familiarity with how it works today could be a liability rather than a strength.
- For the target audience of rural/new/poorly-connected customers, does Facebook even use React to serve them? Did FB5 change anything, or does
m.facebook.com
still not use React? - If we want a version of Kroger.com as fast as the demo, but using the same framework, processes, management, and developers as the existing site — wouldn’t that just become our existing site? We can’t change our personnel, but we can change the technologies we build on.
- Last, but certainly not least: can you make an industry-beating app out of industry-standard parts?
- For the target audience of rural/new/poorly-connected customers, does Facebook even use React to serve them? Did FB5 change anything, or does
- A different way to build together
Pierre is reimagining industry-old primitives for a new developer platform that brings together your entire team to build and ship software. Branches, not pull requests. Bots, not CI. Features you'll love, not the kitchen sink.
- Interoperability: Swift’s Super Power
Swift’s deliberate design choices over the years has resulted in a language that showcases how flexibility and compatibility do not need to come at the cost of usability. One of these design choices was Swift’s focus on native interoperability with other languages. The flexibility that this enables makes it a joy to build rich, native experiences in Swift across a variety of environments.
Traditionally when two languages need to interoperate, the function calls at the boundary between the two languages, also known as the Foreign Function Interface (FFI), will go through C using a library like libffi. This approach has some drawbacks such as incurred runtime performance costs and possibly extra boilerplate code. Instead, Swift embeds a copy of clang, the C and C++ compiler, which is able to directly translate between the languages avoiding penalties in code size and runtime performance. This level of interoperability composes wonderfully with existing systems and enables building complex software atop existing C libraries.
- Deploying Transformers on the Apple Neural Engine
An increasing number of the machine learning (ML) models we build at Apple each year are either partly or fully adopting the Transformer architecture. This architecture helps enable experiences such as panoptic segmentation in Camera with HyperDETR, on-device scene analysis in Photos, image captioning for accessibility, machine translation, and many others. This year at WWDC 2022, Apple is making available an open-source reference PyTorch implementation of the Transformer architecture, giving developers worldwide a way to seamlessly deploy their state-of-the-art Transformer models on Apple devices.
This implementation is specifically optimized for the Apple Neural Engine (ANE), the energy-efficient and high-throughput engine for ML inference on Apple silicon. It will help developers minimize the impact of their ML inference workloads on app memory, app responsiveness, and device battery life. Increasing the adoption of on-device ML deployment will also benefit user privacy, since data for inference workloads remains on-device, not on the server.
In this article we share the principles behind this reference implementation to provide generalizable guidance to developers on optimizing their models for ANE execution. Then, we put these principles into action and showcase how to deploy an example pretrained Transformer model, the popular Hugging Face distilbert, in just a few lines of code. Notably, this model, which works out-of-the-box and on device using Core ML already, is up to 10 times faster and consumes 14 times less memory after our optimizations.
- Precise error typing in Swift
But there are arguments in favor of precise error typing as well. It’s been six years; we should look at those reasons and consider whether it’s time to add precise error typing to Swift. And that’s what I’m about to do.
I’ll spoil the conclusion: I think the answer is “yes”. But it’s a “yes” with a very big caveat. I think the strongest reasons for adding precise error typing relate to (1) the interaction of
throws
with the generics system and (2) the requirements of low-level systems code. And so I think that we, as a community, should continue to strongly push imprecise error typing as the primary way that people ought to write code. Precise error typing will be a tool that programmers have in their toolbox for the cases where it’s really important (mostly, for low-level reliability and performance), and it will solve some expressivity problems for generic libraries. But when you don't need that tool, you should stick to throwingError
.I want to be clear that this is not a guarantee that the feature is coming, or even a plan of attack. The main reason I'm writing this is because it keeps coming up in proposal reviews: there are a lot of library features that need to decide whether and how to accommodate the possibility of precise error typing. So I think it's very important to have a conversation about where we're going with this, and I hope that starts now.
- Swift Macro Testing
Magical testing tools for Swift macros.
- Swift Version
- SQL join flavors
There is more to SQL joins than you might think. Let's explore them a bit.
- Access-level modifiers on import declarations [SE-0409]
Declaring the access level of an imported module
The access level is declared in front of the import declaration using some of the modifiers used for a declaration:
public
,package
,internal
,fileprivate
, andprivate
.A public dependency can be referenced from any declaration and will be visible to all clients. It is declared with the
public
modifier.public import PublicDependency
A dependency visible only to the modules of the same package is declared with the
package
modifier. Only the signature ofpackage
,internal
,fileprivate
andprivate
declarations can reference the imported module.package import PackageDependency
A dependency internal to the module is declared with the
internal
modifier. Only the signature ofinternal
,fileprivate
andprivate
declarations can reference the imported module.internal import InternalDependency
A dependency private to this source file is declared with either the
fileprivate
or theprivate
modifier. In both cases the access is scoped to the source file declaring the import. Only the signature offileprivate
andprivate
declarations can reference the imported module.fileprivate import DependencyPrivateToThisFile private import OtherDependencyPrivateToThisFile
The
open
access-level modifier is rejected on import declarations. - Self-Hosted macOS CI on Apple Silicon with Cilicon
TL;DR: We released a new macOS app called Cilicon, which provisions and runs ephemeral virtual machines for CI. Using it, we were able to switch to self-hosted Actions Runners and speed up our CI by 3x while giving some of our damaged M1 MacBook Pro devices a second life.
- Device LLMs in Apple Devices
I believe that ML is a new way to build software, and I know that many Swift developers want to incorporate AI features in their apps. The ML ecosystem has matured a lot, with thousands of models that solve a wide variety of problems. Moreover, LLMs have recently emerged as almost general-purpose tools – they can be adapted to new domains as long as we can model our task to work on text or text-like data. We are witnessing a defining moment in computing history, where LLMs are going out of research labs and becoming computing tools for everybody.
However, using an LLM model such as Llama in an app involves several tasks which many people face and solve alone. We have been exploring this space and would love to continue working on it with the community. We aim to create a set of tools and building blocks that help developers build faster.
Today, we are publishing this guide to go through the steps required to run a model such as Llama 2 on your Mac using Core ML. We are also releasing alpha libraries and tools to support developers in the journey. We are calling all Swift developers interested in ML – is that all Swift developers? – to contribute with PRs, bug reports, or opinions to improve this together.
- Working With UIViewRepresentable
Here are two rules for working with representables:
- When updating a UIView in response to a SwiftUI state change, we need to go over all the representable’s properties, but only change the UIView properties that need it.
- When updating SwiftUI in response to a UIKit change, we need to make sure these updates happen asynchronously.
If we don’t follow these rules, there are a few issues we might see:
- The dreaded “Modifying state during view update, this will cause undefined behavior” warning
- Unnecessary redraws of our UIViewRepresentable, or even infinite loops
- Strange behavior where the state and the view are a little bit out of sync
In my testing, these issues are becoming less relevant with UIKit, but are very relevant when dealing with AppKit. My guess is that UIKit components
- Moving from 1Password to iCloud Keychain
In this post, I will detail how I moved my data out of 1Password and into iCloud Keychain and use the new Passwords preference pane introduced in macOS Monterey. I have only recently switched from 1Password to iCloud Keychain so this post will not dive into the pros and cons of the two.
- Implementing Your Own Crash Reporter
I strongly advise against implementing your own crash reporter. It’s very easy to create a basic crash reporter that works well enough to debug simple problems. It’s impossible to implement a good crash reporter, one that’s reliable, binary compatible, and sufficient to debug complex problems. The bulk of this post is a low-level explanation of that impossibility.
Earlier I said “It’s impossible to implement a good crash reporter”, and I want to explain why I’m confident enough in my conclusions to use that specific word. There are two fundamental problems here:
- On iOS (and the other iOS-based platforms, watchOS and tvOS) your crash reporter must run inside the crashed process. That means it can never be 100% reliable. If the process is crashing then, by definition, it’s in an undefined state. Attempting to do real work in that state is just asking for problems [1].
- To get good results your crash reporter must be intimately tied to system implementation details. These can change from release to release, which invalidates the assumptions made by your crash reporter. This isn’t a problem for the Apple crash reporter because it ships with the system. However, a crash reporter that’s built in to your product is always going to be brittle.
- Symbolicating SwiftUI (and any Apple Framework)
Have you ever noticed that crash logs sometimes don't make much sense or are missing some symbols? Unlike traditional UIKit applications, Apple does not provide debug symbols (dSYMs) for SwiftUI. This means that any crash containing SwiftUI addresses in the stack trace will not be symbolicated.
We've discovered a way to symbolicate any Apple framework and want to share it with everyone.
- SwiftUI Sensory Feedback
Before iOS 17 if you wanted to give haptic feedback to a user from a SwiftUI view you’d use one of the UIKit (or AppKit) feedback generators.
In iOS 17, Apple added a range of sensory feedback view modifiers directly to SwiftUI to play haptic and/or audio feedback.
- Artifactory, Your Swift Package Repository
JFrog now offers the first and only Swift binary package repository, enabling developers to use JFrog Artifactory for resolving Swift dependencies instead of enterprise source control (Git) systems. Swift developers can benefit from Artifactory’s robust binary management and the ways that it contributes to stable and efficient CI/CD, massive scalability, and securing the software supply chain..
- Is dispatchPrecondition a reasonable way to implement an @unchecked Sendable type?
In general, the right thing to do depends on why your class is safe:
- If your class instances can be safely referenced by multiple threads because their stored properties are all immutable
let
s, your class can just beSendable
. - If your class instances can be safely referenced by multiple threads because in practice their stored properties are all immutable, but for some reason (e.g. a complex initialization pattern that completes before the object is shared across threads) some of the properties have to be declared as mutable
var
s, that is a perfectly reasonable use of@unchecked Sendable
. Consider adding some sort of lifecycle assertion to your setters, e.g. a "this is immutable now" flag. - If your class instances can be safely referenced by multiple threads because their mutable storage is only actually accessed from a globally-singleton thread, your class should be associated with a global actor.
- If your class instances can be safely referenced by multiple threads because their mutable storage is only actually accessed under a lock, that is a reasonable use of
@unchecked Sendable
. This is an important pattern that we're working on safe ways to express. - If your class instances can't generally be safely referenced by multiple threads, and in fact they aren't referenced by multiple threads and just get created, used, and destroyed on a single thread, they should not have to be Sendable at all. In this case, it's worth figuring out why you think you need to do so. It's possible that you're actually doing something dangerous, or maybe you've got some funny sort of concurrent context that Swift doesn't understand behaves like an isolated serial executor. Consider if there's an alternative way to express your pattern in a way that Swift will understand.
- If your class instances can't generally be safely referenced by multiple threads, but instances do need to be moved between threads occasionally, you should not use
@unchecked Sendable
on the class. Instead, you should suppress the warning locally by "smuggling" the object across the sendability boundary: make a value of an@unchecked Sendable struct
that holds the object, then send that instead. This is safe as long as you really do stop using the object in the original context (and only transfer it to one context at a time), and it's much better than pretending that any send is safe. This is a very important pattern that we're actively working on safe ways to express. - If your class instances can be safely referenced by multiple threads because their mutable storage is only actually accessed from one of the threads at a time, but that thread isn't globally singleton, the accesses aren't mediated by something like a lock, and you really do maintain active references on multiple threads... I mean, I'm willing to assume that you've got some justification for why this is being done safely, but this seems like a very treacherous pattern, and it's hard to imagine Swift ever finding a way to support it safely. Consider whether you can find a more structured way to express this. If not, you're going to have to just use
@unchecked Sendable
on the class and accept that you're losing out on concurrency safety.
- If your class instances can be safely referenced by multiple threads because their stored properties are all immutable
- Selective.kt
package arrow.typeclasses
import arrow.Kind
import arrow.core.Either
import arrow.core.Left
import arrow.core.Right
import arrow.core.andThen
import arrow.core.left
import arrow.core.right
/**
* ank_macro_hierarchy(arrow.typeclasses.Selective)
*/
interface Selective<F> : Applicative<F> {
fun <A, B> Kind<F, Either<A, B>>.select(f: Kind<F, (A) -> B>): Kind<F, B>
private fun Kind<F, Boolean>.selector(): Kind<F, Either<Unit, Unit>> =
map { bool -> if (bool) Unit.left() else Unit.right() }
fun <A, B, C> Kind<F, Either<A, B>>.branch(fl: Kind<F, (A) -> C>, fr: Kind<F, (B) -> C>): Kind<F, C> {
val nested: Kind<F, Either<A, Either<B, Nothing>>> = map { it.map(::Left) }
val ffl: Kind<F, (A) -> Either<Nothing, C>> = fl.map { it.andThen(::Right) }
return nested.select(ffl).select(fr)
}
fun <A> Kind<F, Boolean>.whenS(x: Kind<F, () -> Unit>): Kind<F, Unit> =
selector().select(x.map { f -> { _: Unit -> f() } })
fun <A> Kind<F, Boolean>.ifS(fl: Kind<F, A>, fr: Kind<F, A>): Kind<F, A> =
selector().branch(fl.map { { _: Unit -> it } }, fr.map { { _: Unit -> it } })
fun <A> Kind<F, Boolean>.orS(f: Kind<F, Boolean>): Kind<F, Boolean> =
ifS(just(true), f)
fun <A> Kind<F, Boolean>.andS(f: Kind<F, Boolean>): Kind<F, Boolean> =
ifS(f, just(false))
}
- A Day in the Life of a SwiftUI View
There is a lot more I wanted to talk about. And I think the most important concept here is understanding how the code translates into trees and how you can then use those trees for state management, for layout, and many other things.
- The mobile engineering book that every app developer should read.
Improve the way you work and strengthen your skills as an experienced mobile engineer.
- TECH STACK AT AMO
We’ve found success going deep in code sharing across the entire stack throughout our past experiences. As code sharing is simpler in a monorepo, we moved in that direction after many years of painful segregated code sharing practices. amo is now one single monorepo containing all projects and built using the same build system: Bazel (an open-source port of Google Blaze).
- What's nonce entanglement?
Short guide on how to get a generator-apnonce pair for A12+ iOS devices (both jailbroken and non-jailbroken).
- How To Visualize The Safe Area
One of the interesting things is that we can visualize the safe area using an overlay and a geometry reader. We can add ignoresSafeArea to the geometry reader. Inside the geometry reader, we get access to the size of the safe area insets as well as the safe area size itself.
- Swift’s closure capturing mechanics
While it’s common to hear over-simplified rules like “Always use
weak
references within closures”, writing well-performing and predictable apps and systems often requires a bit more nuanced thinking than that. Like with most things within the world of software development, the best approach tends to be to throughly learn the underlying mechanics and behaviors, and then choose how to apply them within each given situation. - Uploading Streams of Data
Streaming media apps and long-running apps that send continual updates use an ongoing stream to upload data, rather than sending a single block of data or a flat file. You can configure an instance of URLSessionUploadTask (a subclass of URLSessionTask) to work with a stream that you provide, and then fill this stream with data indefinitely.
The task gets the stream by calling your session’s delegate, so you need to create a session and set your own code as its delegate.
- OSStatus.com
Look up Apple API errors quickly!
- How to check if you use a required reason API
Apple classified several APIs that can be misused to access device signals to try to identify the device or user (a.k.a fingerprinting).
The APIs were grouped as follows:
- File timestamp APIs
- System boot time APIs
- Disk space APIs
- Active keyboard APIs
- User defaults APIs
The actual list of "required reason API", consisting of
UserDefaults
,ProcessInfo.systemUptime
and many others, can you find here. - Migrating from the Observable Object protocol to the Observable macro
Update your existing app to leverage the benefits of Observation in Swift.
- Improve the build times of your SPM Packages and your apps
Clean Builds
: Clean builds, also known as full builds, involve compiling the entire codebase from scratch, regardless of whether any changes have been made. To improve clean builds’ time:- Check the Improve Compile Time in Xcode Projects section
- Check the Improve Compile Time in SPM Packages section
- Check the Build with Timing Summary + Recent Build TimeLine section
Incremental Builds
: Incremental builds involve compiling only the code that has changed since the last build. To improve incremental builds’ time:- Use modules (SPM Packages work great)
- Use the correct Access Level in your code
- Check the Build with Timing Summary + Recent Build TimeLine section
- Representing haptic patterns in AHAP files
Understand the Apple Haptic and Audio Pattern (AHAP) file format.
AHAP is a JSON-like file format that specifies a haptic pattern through key-value pairs, analogous to a dictionary literal, except in a text file. You add an AHAP file to your Xcode project bundle like any other file resource, such as an audio file or an image.
- Introducing Puddles — A Native SwiftUI App Architecture
That's enough of a preamble. Let's get into the architecture itself. There will be dedicated articles for every aspect of Puddles and you can find a more thorough and detailed overview here or in the repository. The following is just meant to be a quick collection of the key ideas of the architecture.
Puddles suggests an architecture that separates your code base into 4 distinct layers, each with its own responsibilities and functions, encouraging a modular and maintainable project structure for your app.
- What does it mean for a monad to be strong?
This is much more like a workflow. Using
strength
we can rewrite any (monadic) do expression as a left-to-right workflow, with the cost of having to throw in some applications ofstrength
to carry along all of the captured variables. It's also using a composition of arrows in the Kleisli category.A monad with a strength function is called a strong monad. Clearly all Haskell monads are strong as I wrote
strength
to work with any Haskell monad. But not all monads in category theory are strong. It's a sort of hidden feature of Haskell (and the category Set) that we tend not to refer to explicitly. It could be said that we're implicitly using strength whenever we refer to earlier variables in our do expressions. - Explicit Module Builds, the new Swift Driver, and SwiftPM
Explicit module builds are an attempt to move the compilation of textual modules into binary modules out of the Swift compiler instance that imports the module, and up into the build system as an explicit compilation step. The build system is then responsible for scheduling the compilation, checking timestamps on inputs (for incremental builds), and ensuring that all of the binary modules needed by a Swift compilation job have already been built before that compilation job executes.
Explicit module builds are meant to eliminate the problems with implicit module builds, improving parallelism, reducing redundant work among Swift compiler instances, and enabling new technologies such as distributed builds. There are a number of technologies that we are working on in the Swift compilation stack to enable explicit module builds.
- Streaming Multipart Requests
Foundation’s URL loading is robust. iOS 7 brought the new URLSession architecture, making it even more robust. However, one thing that it’s never been able to do natively is multipart file uploads.
- Easy multipart file upload for Swift
Let me show you how to create HTTP requests using multipart (form data) body without a third party library. Simple solution.
- Leaving Haskell behind
So, I wanted to talk about why I fell away from Haskell. I should say up front: this is a piece about why I left Haskell, and not about why you should. I don't think people are wrong for using Haskell, or that Haskell is bad. In fact, if I've written this piece the way I hope to write it, I would hope that people read it and come away with a desire to maybe learn Haskell themselves!
- dependent-sum
Dependent sums and supporting typeclasses for comparing and displaying them
- dependent-map
This library defines a dependently-typed finite map type. It is derived from
Data.Map.Map
in thecontainers
package, but rather than (conceptually) storing pairs indexed by the first component, it storesDSum
s (from thedependent-sum
package) indexed by tag. - macOS 0day: App Management
I'm finally un-redacting the 6th way, and ironically, it's the app sandbox. I discovered—almost by accident—that a sandboxed app could modify files that it shouldn't be able to modify: files inside the bundle of a notarized app that were supposedly protected by App Management security.
Of course a sandboxed app has somewhat limited access to the file system, although it's notable that the /Applications folder is included within the sandbox. Regardless, the initial extent of the sandbox is not really an issue for an attacker, because a non-sandboxed app can open files in a sandboxed app, thereby extending the latter's sandbox.
To demonstrate the bypass, I've created a sample Xcode project that you can download.
- An introduction to fibrations, topos theory, the effective topos and modest sets
Abstract: A topos is a categorical model of constructive set theory. In particular, the effective topos is the categorical `universe' of recursive mathematics. Among its objects are the modest sets, which form a set-theoretic model for polymorphism. More precisely, there is a fibration of modest sets which satisfies suitable categorical completeness properties, that make it a model for various polymorphic type theories.
- Why Swift Reference Types Are Bad for App Startup Time
The app launch experience is the first impression you make on a user. Every millisecond they wait for your app to start is valuable time they could spend elsewhere. If your app has high engagement and is used multiple times a day then users have to wait for launch over and over. Apple recommends the first frame be drawn in under 400ms. This ensures your app is ready to be used when Springboard’s app open animation finishes.
With only 400ms to spare, developers need to be very careful not to accidentally increase app startup time. However, app launch is such a complicated process with so many moving parts that it’s difficult to know what exactly contributes to it. I started diving deeper into the relationship between app binary size and startup time while working on Emerge, the app size profiler. In this post, I’ll demystify one of the more esoteric aspects of app launch and show you how Swift reference types contribute to the binary size and slower app start times.
- Dead Code Detection With Reaper
Maybe a bit dramatic, but I don't think it would be far from the truth to say that all apps have some dead code. There are quite a few benefits to removing this code. Unsurprisingly, dead code can affect app size and compile time, but excessive dead code also introduces complexity to a codebase and slows developer productivity.
Let's say you're updating a function and need to modify all call sites to work with the new function signature. This time is wasted if the call sites are dead. Dead code inherently increases the line count of a codebase, which is correlated to the number of bugs.
There are even performance implications for having dead code take up memory in your iOS app, which I’ve mentioned in articles about fixups and order files. Emerge helps reduce the complexity of apps and infrastructure, including by finding dead code such as protocols without any conformances. This is done with static analysis.
Reaper, Emerge’s new iOS framework, goes beyond static analysis by detecting unused code at runtime. This extra dead code detection helps to build better, simpler apps.
In this post, we’ll look at what dead code is and how runtime detection expands the amount we can find.
- Reaper
Reaper is an SDK that you can put into your production or alpha users' apps to report which Swift and Objective-C classes were used for each user session. We take those reports and generate a list of all the classes in the binary, for each version of your app. The SDK will detect unused classes within the main binary specifically, not in dynamic frameworks. It's easy to integrate, either as a standalone binary or as a Cocoapod, and adds very little overhead to your app.
Reaper supports iOS 15, 16, and 17. It supports all classes written in Objective-C and most classes written in Swift.
- The cost of convenience
It is tempting to build abstractions so developers have to do less and build more. However, this can easily end up causing frustrations with developers if not done right.
Whenever I take a library or a framework for a test drive, work through their “Getting Started” guide or browse the example code, I try to observe my own reaction. Whenever something makes me go “this feels wrong”, I make note of it and try to distill what I would have done differently. In this blog post, I try to figure out what I think makes a good developer experience.
- How to Get Your Fucking Money Back: paperback
Be forewarned: Despite its title, this book contains absolutely no helpful advice for obtaining refunds.
Instead, a cast of fictional characters and Ritcher’s alter egos regale you with adventures from his storied life. Almost none of it is true.
You’ll read about how he served in the Belgian National Guard, launched the Burger Chef restaurant chain, hosted the hit TV show Animal Autopsy and spent several years married to Kirsten Dunst during her two terms as governor of Kentucky.
The book is full of secret nuggets, including another book called Presidential Fun Facts & Trivia, information on bird spotting, proper table settings and a full 90 pages of About the Author (which includes a little detour called About the Author’s Dogs.
How to Get Your Fucking Money Back is an absurd, heavily footnoted, 154-page ride that gleefully disregards reality, the rules of storytelling and, occasionally, some common respect for the English language.
- Open Terraform — A fork of pre BSL Terraform
Terraform enables you to safely and predictably create, change, and improve infrastructure. This is an open-source fork of Hashicorp's Terraform that keeps the MPL license, following Hashicorp's announcing change of license to BSL. The fork is created and maintained by Digger.dev, an open-source CI runner for IaC.
- Swift Forums — About the GRDB category
GRDB is a production-ready database library for Swift, based on SQLite.
It provides raw access to SQL and advanced SQLite features, because one sometimes enjoys a sharp tool. It has robust concurrency primitives, so that multi-threaded applications can efficiently use their databases. It grants your application models with persistence and fetching methods, so that you don't have to deal with SQL and raw database rows when you don't want to.
See Why Adopt GRDB? 103 if you are looking for your favorite database library.
This forum is intended to answer community questions, raise your interest, share stories, experience, and best practices.
- Adaptative Views That Fit Anywhere in SwiftUI
In the constantly evolving world of iOS development, SwiftUI has undeniably brought forth a revolution in how we approach interface design. The introduction of the ViewThatFits struct simplifies adaptive layout construction, eradicating the tedious task of handling different screen sizes and frames manually.
By comprehending the nuances between proposed and ideal sizes, developers can leverage the power of SwiftUI to automatically select the most fitting view based on its parent’s dimensions. This not only aids in the creation of more responsive apps but also reduces redundancy in code, promoting cleaner, more maintainable projects.
- How should I read type system notation?
The notation used to describe type systems varies from presentation to presentation, so giving a comprehensive overview is impossible. However, most presentations share a large, common subset, so this answer will attempt to provide a foundation of enough of the basics to understand variations on the common theme.
- Open-source production-like development infrastructure.
Allow each engineer to provision their own "staging" environment using plain Terraform files.
Layerform helps engineers create reusable environment stacks using plain Terraform files (the actual OSS version). Ideal for multiple "staging" environments.
- createPDF(configuration:completionHandler:)
Generates PDF data from the web view’s contents asynchronously.
- Compositionality
Compositionality describes and quantifies how complex things can be assembled out of simpler parts.
Compositionality (ISSN 2631-4444) is an open-access, arXiv-overlay journal for research using compositional ideas in any discipline. For more information, see About.
- Mermaid by Miro Labs
With the Mermaid app, you can easily create and import diagrams with Markdown-inspired syntax. Automate the process of generating complex diagrams without worrying about design and layout.
Key Features:
- Create diagrams with the popular Mermaid syntax
- Easily design any kind of diagram like, Flowcharts, Sequence diagrams, ER diagrams and even C4 architecture
- Copy code from other sources like GitHub or Notion into Miro
- Design and layout is automatically applied
- Diagrams are fully editable
- Incremental migration to concurrency checking
Swift 5.5 introduced mechanisms to eliminate data races from the language, including the
Sendable
protocol (SE-0302) to indicate which types have values that can safely be used across task and actor boundaries, and global actors (SE-0316) to help ensure proper synchronization with (e.g.) the main actor. However, Swift 5.5 does not fully enforceSendable
nor all uses of the main actor because interacting with modules which have not been updated for Swift Concurrency was found to be too onerous. We propose adding features to help developers migrate their code to support concurrency and interoperate with other modules that have not yet adopted it, providing a smooth path for the Swift ecosystem to eliminate data races.
Swift-evolution threads: [Pitch] Staging in Sendable
checking, Pitch #2, Pitch #3
graph TD;
classDef facadeCommand fill:#779fae
classDef command fill:#aec6cf
classDef result fill:#cfcfc4
classDef event fill:#ffb853
classDef domainEvent fill:#ffcb81
classDef integrationEvent fill:#ffdeaf
classDef query fill:#62d862
classDef readModel fill:#77dd77
classDef userInterface fill:#a2e8a2
classDef aggregate fill:#fdfd9d
classDef service fill:#fcfc78
classDef policy fill:#b6a2db
classDef saga fill:#c9bbe5
classDef process fill:#ddd4ee
classDef timer fill:#cfcfc4
classDef person fill:#ffd1dc
classDef system fill:#ffd1dc
classDef comment fill:transparent
FacadeCommand:::facadeCommand --> Command:::command
Result:::result --> Event:::event
DomainEvent:::domainEvent --> IntegrationEvent:::integrationEvent
Query:::query --> ReadModel:::readModel
UserInterface:::userInterface --> Aggregate:::aggregate
Service:::service --> Policy:::policy
Saga:::saga --> Process:::process
Timer:::timer --> Person:::person
System:::system --> Comment:::comment
- Objective-C Internals
Get ready to dive deep into the inner workings of the Objective-C language and runtime! Each post delves into a specific aspect of the language and explores the details of its implementation. I hope you’ll find this valuable to demystify the language, tackle tricky bugs, and optimize your code for performance.
- Getting Started with Plugins [SPM]
This guide provides a brief overview of Swift Package Manager plugins, describes how a package can make use of plugins, and shows how to get started writing your own plugins.
- Git First-Parent
When
git log
encounters a merge commit, it normally follows the history backwards through both parents.But if we say
--first-parent
,git log
will ignore all of the history in the second parent of a merge commit - modellution
Best collaboration platform for Event Storming & Event Modeling
- Flipper Zero
Multi-tool Device for Geeks
Flipper Zero is a portable multi-tool for pentesters and geeks in a toy-like body. It loves hacking digital stuff, such as radio protocols, access control systems, hardware and more. It's fully open-source and customizable, so you can extend it in whatever way you like.
Flipper Zero is a tiny piece of hardware with a curious personality of a cyber-dolphin. It can interact with digital systems in real life and grow while you use it. Explore any kind of access control system, RFID, radio protocols, and debug hardware using GPIO pins
- [Markdown] An option to highlight a "Note" and "Warning" using blockquote (Beta)
> [!NOTE]
> Highlights information that users should take into account, even when skimming.
> [!IMPORTANT]
> Crucial information necessary for users to succeed.
> [!WARNING]
> Critical content demanding immediate user attention due to potential risks.
- SDF
SDF does for SQL what Typescript did for Javascript. Faster Development. Trusted Results. Safety at Scale.
- Swift Compiler Performance
This document is a guide to understanding, diagnosing and reporting compilation-performance problems in the swift compiler. That is: the speed at which the compiler compiles code, not the speed at which that code runs.
While this guide is lengthy, it should all be relatively straightforward. Performance analysis is largely a matter of patience, thoroughness and perseverance, measuring carefully and consistently, and gradually eliminating noise and focusing on a signal.
- TSPL-doccarchive
Visit the history versions of TSPL(The Swift Programming Language) with ease.
- Obstructions to Compositionality
Compositionality is at the heart of computer science and several other areas of applied category theory such as computational linguistics, categorical quantum mechanics, interpretable AI, dynamical systems, compositional game theory, and Petri nets. However, the meaning of the term seems to vary across the many different applications. This work contributes to understanding, and in particular qualifying, different kinds of compositionality. Formally, we introduce invariants of categories that we call zeroth and first homotopy posets, generalising in a precise sense the π0 and π1 of a groupoid. These posets can be used to obtain a qualitative description of how far an object is from being terminal and a morphism is from being iso. In the context of applied category theory, this formal machinery gives us a way to qualitatively describe the "failures of compositionality", seen as failures of certain (op)lax functors to be strong, by classifying obstructions to the (op)laxators being isomorphisms. Failure of compositionality, for example for the interpretation of a categorical syntax in a semantic universe, can both be a bad thing and a good thing, which we illustrate by respective examples in graph theory and quantum theory.
- Proceedings Fifth International Conference on Applied Category Theory
The Fifth International Conference on Applied Category Theory took place at the University of Strathclyde on 18−22 July 2022, following the previous meetings at Leiden (2018), Oxford (2019), MIT (2020, fully online), and Cambridge (2021). It was preceded by the Adjoint School 2022 (11−15 July), a collaborative research event in which junior researchers worked on cutting-edge topics under the mentorship of experts. The conference comprised 59 contributed talks, a poster session, an industry showcase session, and a session where junior researchers who had attended the Adjoint School presented the results of their research at the school. Information regarding the conference may be found at https://msp.cis.strath.ac.uk/act2022.
- DocC Tutorial for Swift: Automating Publishing With GitHub Actions
Learn how to automate export a Docc archive file using GitHub Actions, and publish it on the internet using GitHub Pages as a static website host.
- Swift Function Body Macros
This proposal introduces function body macros, which are attached macros that can create or augment a function (including initializers, deinitializers, and accessors) with a new body.
- swift server + dev containers
In this post you will learn how to configure your Swift development environment for Linux using Dev Containers VSCode extension. This unlocks the ability to build, run, and debug Swift apps on Linux.
- Describing use of required reason API
Ensure your use of covered API is consistent with policy.
Some APIs that your app uses to deliver its core functionality — in code you write or included in a third-party SDK — have the potential of being misused to access device signals to try to identify the device or user, also known as fingerprinting. Regardless of whether a user gives your app permission to track, fingerprinting is not allowed. Describe the reasons your app or third-party SDK on iOS, iPadOS, tvOS, visionOS, or watchOS uses these APIs, and check that your app or third-party SDK only uses the APIs for the expected reasons.
For each category of required reason API that your app or third-party SDK uses, add a dictionary to the
NSPrivacyAccessedAPITypes
array in your app or third-party SDK’s privacy manifest file that reports the reasons your app uses the API category. If you use the API in your app’s code, then you need to report the API in your app’s privacy manifest file. If you use the API in your third-party SDK’s code, then you need to report the API in your third-party SDK’s privacy manifest file. Your third-party SDK can’t rely on the privacy manifest files for apps that link the third-party SDK, or those of other third-party SDKs the app links, to report your third-party SDK’s use of required reasons API. - Lean FRO
We are excited to share the news of the Lean Focused Research Organization (FRO)! A new nonprofit dedicated to advancing the Formal Mathematics revolution, we aim to tackle the challenges of scalability, usability, and proof automation in the Lean proof assistant. Our 5-year mission is to empower Lean towards self-sustainability.
- Push Notifications Options in SwiftUI
Implementing push notifications in SwiftUI is a potent tool for boosting user engagement and providing real-time updates. The UNUserNotificationCenter is the hero of our push notification story, facilitating every aspect of notifications from scheduling to user interaction.
The vast variety of authorization options in Swift, such as alert, badge, sound, CarPlay, provisional, critical alert, and providesAppNotificationSettings, allows developers to create a custom user experience, tailoring notifications to specific app needs and user preferences. However, it’s important to implement these options judiciously to ensure a seamless and unobtrusive user experience.
- Iterative multisets, iterative sets, and iterative ordinals.
Some of the development of "Set-Theoretic and Type-Theoretic Ordinals Coincide" is carried out but using Gylterud's construction of the cumulative hierarchy 𝕍 as iterative sets, instead of (axiomatically) working with the higher inductive presentation. The type 𝕆 of hereditarily transitive sets is the type of iterative ordinals and corresponds to 𝕍ᵒʳᵈ in the original development Ordinals.CumulativeHierarchy.
- Vim Mode: Find Current Word
In vim mode position the cursor on a word and press * to start to search for that word in the current file.
- Format Styles In Excruciating Detail
Swift’s
FormatStyle
andParseableFormatStyle
are the easiest way to convert Foundation data types to and from localized strings. Unfortunately Apple hasn’t done a great job in documenting just what it can do, or how to use them. - Developer Duck AI for Xcode
Powered by ChatGPT & GPT-4 API
Developer Duck is an AI-powered programming assistant that helps you with your programming tasks. Including features like code suggestions, completion, analysis, and refactoring, Developer Duck is faster than searching the web. Try it for free and put it to the test.
- Beginner's guide on Flutter for iOS developers
Learn the main concepts of Flutter from a native iOS developer's point of view.
- How to Use Swift Package Manager to Save Gigabytes of Network Traffic and Disk Space
Use SPM to store dependency checkouts in a repository and do it better than CocoaPods
- JavaScript Macros in Bun
Macros are a mechanism for running JavaScript functions at bundle-time. The value returned from these functions are directly inlined into your bundle.
For small things where you would otherwise have a one-off build script, bundle-time code execution can be easier to maintain. It lives with the rest of your code, it runs with the rest of the build, it is automatically paralellized, and if it fails, the build fails too.
- Stack as the variable binding environment: lexical binding via dynamic binding, strict and lazy
The most familiar, explained in any textbook approach to dealing with variable references in higher-order programs is variable binding environment: an association of variable names with their bound values. In an interpreter (the eval function), the environment is one of its arguments. Compiled functions receive the environment as an extra argument. Terms with variables are commonly thought to mean functions from the environment to the value domain.
This article demonstrates a different, unconventional approach to variable references, coming from the observation that a (let-)bound variable can only be used while the control remains within the corresponding let-expression body. In interpreter terms, a variable may be accessed only while the interpreter is still handling the let-form, which remains on the interpreter stack. Therefore, to find the value associated with the bound variable we search the stack — or, better, just point to the right place on the stack that stores that value.
That is a very attractive idea, which seems first to come to mind when implementing higher-order languages. It was indeed first that came to mind to J. McCarthy and A. Turing. Alas, the idea — now called dynamic binding — is flawed (as Turing soon realized). To regard functions as first-class, to be able to pass them as arguments and return as results, lexical binding is indispensable.
This article demonstrates that, perhaps surprisingly, lexical binding can be implemented via dynamic binding, in strict and lazy settings.
The main advantage of this alternative approach is making variables a modular feature: variables and (first-class) functions can be introduced to a first-order language without any changes to the latter, without any need to re-write the interpretation of the first-order fragment (numbers, strings, etc.) to pass the environment. We may write extensible interpreters and compilers. Another application is the surprisingly simple implementation of staging.
Dynamic binding can be implemented in many ways. One particular implementation, in terms of delimited control, turns out particularly insightful. Incidentally, it demonstrates the need for multi-shot (non-affine) delimited continuations — perhaps the first non-trivial use of such delimited continuations aside from non-determinism.
Another insight is that a let-expression — often considered a mere syntax sugar in lambda calculus — turns out more fundamental than the lambda abstraction.
- AWS Serverless Application Model — Swift Server Templates
The AWS Serverless Application Model (SAM) is an open-source framework for building serverless applications. This page shows you how to use SAM to deploy Server-side Swift applications to AWS. Each application uses AWS Lambda Functions written in Swift. The functions use the AWS SDK for Swift and the Swift AWS Lambda Runtime.
- OrbStack — Say goodbye to slow, clunky containers and VMs
Seamless and efficient Docker and Linux on your Mac. Glide through your work faster with our Docker Desktop alternative.
- Understanding SVG Paths
If you've ever looked at the SVG code for an icon before, you might have noticed that they're usually made up of a bunch of
path
elements, each with a crypticd
attribute. - ClamXAV — Put a stop to malware, not to your Mac
Keep your Mac safe with ClamXAV, the trusted anti-virus and malware scanner for macoS
- Uxn
The Uxn ecosystem is a little personal computing stack, created to host ours tools and games, programmable in its own unique assembly language.
It was designed with an implementation-first mindset with a focus on creating portable graphical applications, the distribution of Uxn projects is akin to sharing game roms for any classic console emulator.
To learn more, read about the uxn design, see the VM specs, or the IO specs.
- Timely Computation — Conal Elliott
This paper addresses the question “what is a digital circuit?” in relation to the fundamentally analog nature of actual (physical) circuits. A simple informal definition is given and then formalized in the proof assistant Agda. At the heart of this definition is the timely embedding of discrete information in temporally continuous signals. Once this embedding is defined (in constructive logic, i.e., type theory), it is extended in a generic fashion from one signal to many and from simple boolean operations (logic gates) to arbitrarily sophisticated sequential and parallel compositions, i.e., to computational circuits.
Rather than constructing circuits and then trying to prove their correctness, a compositionally correct methodology maintains specification, implementation, timing, and correctness proofs at every step. Compositionality of each aspect and of their combination is supported by a single, shared algebraic vocabulary and related by homomorphisms. After formally defining and proving these notions, a few key transformations are applied to reveal the linearity of circuit timing (over a suitable semiring), thus enabling practical, modular, and fully verified timing analysis as linear maps over higher-dimensional time intervals.
An emphasis throughout the paper is simplicity and generality of specification, minimizing circuit-specific definitions and proofs while highlighting a broadly applicable methodology of scalable, compositionally correct engineering through simple denotations and homomorphisms.
- Native Plant Finder
Search by zip code to find plants that host the highest numbers of butterflies and moths to feed birds and other wildlife where you live.
- All about Item Providers
The
NSItemProvider
class in Foundation is a powerful abstraction for making data available across processes that are otherwise isolated from one another. I hope this post can be a one-stop reference for developers who want a solid understanding how item providers work, and how to use the API in a modern way. - Understanding Sockets
Sockets are a way to enable inter-process communication between programs running on a server, or between programs running on separate servers. Communication between servers relies on network sockets, which use the Internet Protocol (IP) to encapsulate and handle sending and receiving data.
Network sockets on both clients and servers are referred to by their socket address. An address is a unique combination of a transport protocol like the Transmission Control Protocol (TCP) or User Datagram Protocol (UDP), an IP address, and a port number.
In this tutorial you will learn about the following different types of sockets that are used for inter-process communication:
- Stream sockets, which use TCP as their underlying transport protocol
- Datagram sockets, which use UDP as their underlying transport protocol
- Unix Domain Sockets, which use local files to send and receive data instead of network interfaces and IP packets.
In each section of this tutorial you will also learn how to enumerate the respective socket types on a Linux system. You’ll examine each type of socket using a variety of command line tools.
- SwiftUI Data Flow 2023
SwiftUI is a reactive framework where the data drives the UI. In 2019, I wrote a post detailing how I manage the various forms of data flow through a SwiftUI app, and with the help of others in the community, I iterated over this until I had a good understanding of the concepts and which methods you should use when. In 2021, I updated the post to cover the minor changes, but there have been no major modifications since then.
At WWDC 2023, things changed a lot! With the introduction of Swift macros, the SwiftUI team was able to reduce the number of property wrappers need to send data around, and remove a lot of boilerplate code.
- One-shot Algebraic Effects in Swift
You could build an even closer analog in terms of async, since
with*Continuation
gives you a delimited continuation for the task (albeit a one-shot continuation, unlike the multi-shot continuations that "pure" algebraic effect systems provide in functional languages). You could for example store the effect handler in task-local state, and have the effect operations be functions that usewithCheckedContinuation
to access the current handler and resume the task with the result:
class State {
var value: Int
}
@TaskLocal var stateHandler: State?
// Run the block with a state handler
func with(state: State, _ body: () async throws -> R) rethrows -> R {
stateHandler = state
defer { stateHandler = nil }
return try await body()
}
// Access the current state
var stateValue: Int {
get async {
return withCheckedContinuation { cc in
cc.resume(returning: stateHandler!.value)
}
}
}
- FocusedValue
A property wrapper for observing values from the focused view or one of its ancestors.
If multiple views publish values using the same key, the wrapped property will reflect the value from the view closest to focus.
- Advanced macOS Command-Line Tools
macOS is fortunate to have access to the huge arsenal of standard Unix tools. There are also a good number of macOS-specific command-line utilities that provide unique macOS functionality. To view the full documentation for any of these commands, run
man <command>
. - LeanDojo: Machine Learning for Theorem Proving in Lean
LeanDojo is a Python library for learning–based theorem provers in Lean, supporting both Lean 3 and Lean 4. It provides two main features:
- Extracting data (proof states, tactics, premises, etc.) from Lean repos.
- Interacting with Lean programmatically.
- Swift values and locations
A value is what you can return from a call, pass as a (non-
inout
) argument, and so on. Ignoring reference types for a second, you can talk about values independently of concepts like memory. Fundamental types can be thought of as fundamental values, like particular integers and strings, andstruct
s can broken down recursively into the component values they store in their stored properties. For example, I might say that a particular value isBall(diameter: .03, color: Color.orange)
. Here I've written the value as if I were calling a memberwise initializer with all the values of the stored properties; this works to denote the value even if I didn't actually build it that way, or even if my type doesn't actually have a memberwise initializer.A location is part of the memory of the abstract machine. Every location has a type, and it stores a value of its type. For example, when you declare a mutable local variable, a new location is created dynamically when that variable comes into scope, and it is destroyed when the variable goes out of scope (and all the captures of it go away). Creating a location of a struct type means creating locations for all the stored properties of that struct.
- OpenAPI package manager
AI is fundamentally changing the way we live, work, and build software. It has the potential to be the biggest platform shift since the iphone and mobile.
With mobile we learned the painful lesson of the Apple app-store, controlled by a single monopolistic company, stifling innovation and entrepreneurship.
AI, our new platform, needs it's own app-store. An unrestricted app-store built upon the open web and the OpenAPI specification.
We engineers currently have a slim chance of creating this app-store layer before some large corporation does it. We must seize this chance.
That's why we're building openpm.ai, an open source package-manager for OpenAPI files. AIs can use consume packages from openpm in a similar fashion to how ChatGPT plugins work. Ultimately, AIs can use openpm to discover and interact with the world via APIs.
Everything we release is under the MIT license. We will never charge a transaction fee for our services. We will never wield editorial control. We will only remove packages that are scams or illegal under US law. At any point you can choose to export all of our packages and run them on your own server.
- Leading through uncertainty
Design is not just a way to make sense of the world; design helps the world make sense. It takes fierce optimism to face challenges and see them as opportunities for learning, growth and change.
- Designing for visionOS
When people wear Apple Vision Pro, they enter an infinite 3D space where they can engage with your app or game while staying connected to their surroundings.
As you begin designing your app or game for visionOS, start by understanding the fundamental device characteristics and patterns that distinguish the platform. Use these characteristics and patterns to inform your design decisions and help you create immersive and engaging experiences.
Space. Apple Vision Pro offers a limitless canvas where people can view virtual content like windows, volumes, and 3D objects, and choose to enter deeply immersive experiences that can transport them to different places.
Immersion. In a visionOS app, people can fluidly transition between different levels of immersion. By default, an app launches in the Shared Space where multiple apps can run side-by-side and people can open, close, and relocate windows. People can also choose to transition an app to a Full Space, where it’s the only app running. While in a Full Space app, people can view 3D content blended with their surroundings, open a portal to view another place, or enter a different world.
Passthrough. Passthrough provides live video from the device’s external cameras, and helps people interact with virtual content while also seeing their actual surroundings. When people want to see more or less of their surroundings, they use the Digital Crown to control the amount of passthrough.
Spatial Audio. Vision Pro combines acoustic and visual-sensing technologies to model the sonic characteristics of a person’s surroundings, automatically making audio sound natural in their space. When an app receives a person’s permission to access information about their surroundings, it can fine-tune Spatial Audio to bring custom experiences to life.
Focus and gestures. In general, people interact with Vision Pro using their eyes and hands. People perform most actions by looking at a virtual object to bring focus to it and making an indirect gesture, like a tap, to activate it. People can also use a direct gesture to interact with a virtual object by touching it with a finger.
Ergonomics. While wearing Vision Pro, people rely entirely on the device’s cameras for everything they see, both real and virtual, so maintaining visual comfort is paramount. The system helps maintain comfort by automatically placing content so it’s relative to the wearer’s head, regardless of the person’s height or whether they’re sitting, standing, or lying down. Because visionOS brings content to people — instead of making people move to reach the content — people can remain at rest while engaging with apps and games.
Accessibility. Apple Vision Pro supports accessibility technologies like VoiceOver, Switch Control, Dwell Control, Guided Access, Head Pointer, and many more, so people can use the interactions that work for them. In visionOS, as in all platforms, system-provided UI components build in accessibility support by default, while system frameworks give you ways to enhance the accessibility of your app or game.
- Apple Design Resources — visionOS
Apple’s initial visionOS design kit for Figma contains a comprehensive set of UI components, views, system interfaces, text styles, color styles, and materials. All of the core ingredients you need to quickly create highly realistic visionOS app designs.
If you have requests, find bugs, or have other feedback for us, please use Feedback Assistant. Select Developer Tools > Apple Design Resources.
Important: Make sure to install the latest version of SF Symbols before using this library.
- Cross-module inlining and specialization
We propose introducing a pair of new attributes,
@inlinable
and@usableFromInline
. The@inlinable
attribute exports the body of a function as part of a module's interface, making it available to the optimizer when referenced from other modules. The@usableFromInline
attribute marks an internal declaration as being part of the binary interface of a module, allowing it to be used from@inlinable
code without exposing it as part of the module's source interface. - XcodeBenchmark
XcodeBenchmark
contains a large codebase to measure the compilation time in Xcode. - What was special about Pivotal?
Was it pairing? TDD? Retros? Or was it that we could write code in peace, without being bitten by possums?
- Little big improvements in Xcode 15
- BuildSettingExtractor
The fastest way to extract Xcode build settings.
BuildSettingExtractor is a free, open-source utility that extracts build settings from an Xcode project into a set of xcconfig files.
When you’re moving Xcode build settings out of your project file and into xcconfig files, this handy utility makes that initial move a lot easier. It’s also an easy way for the curious to take a look at the build settings in a project without fear of accidentally changing them.
- WWDC23 #SwiftUI
Every question + answer in 2023’s #swiftui WWDC Digital Lounge organised for an easy read.
For brevity, any requests from Apple to file a feedback have not been included in the responses. So, it’s worth emphasising that the SwiftUI team encouraged everyone to file a feedback for any unsupported behaviour, because this helps them prioritise their backlog. So, if you can’t get SwiftUI to do x today, please let them know. When you do, describe your use case so they have a clear idea what you’re trying to accomplish (this will help them understand better the general merit of the feature request).
- Interpolate text with custom foreground style in SwiftUI
SwiftUI lets us style portions of text by interpolating
Text
inside anotherText
and applying available text modifiers, such asforegroundColor()
orfont()
.Starting from iOS 17 we can apply more intricate styling to ranges within a
Text
view with foregroundStyle().
struct ContentView: View {
let gradient = LinearGradient(
colors: [.blue, .green],
startPoint: .leading,
endPoint: .trailing
)
var body: some View {
Text("Hello, \(Text("world").foregroundStyle(gradient))!")
.bold()
.font(.title)
.textCase(.uppercase)
}
}
- Abstractions in Context
Learn Haskell abstractions the easy way — with real-world examples and context. You'll learn common patterns in Haskell, how to implement them yourself, and what their benefits and drawbacks are.
This short book is meant for anyone who already has a basic working understanding of Haskell, but is looking for intermediate-level knowledge.
- MediaExtension
This framework provides a means for developers to create format readers and video decoders for media that the system doesn’t natively support.
MediaExtension format readers encapsulate media assets that the system doesn’t natively support so that the system can recognize them. MediaExtension video decoders decode video formats that the system doesn’t natively support. Developers need to build format readers and video decoders as ExtensionKit bundles and embed them in a host app. Once a user installs and runs the host app, the embedded extensions become available to any app on the user’s system that opts in to using them.
- Improving app responsiveness
Create a more immediate user experience by removing hangs and hitches from your app’s user interface.
An app that responds instantly to users’ interactions gives an impression of supporting their workflow. When the app responds to gestures and taps in real time, it creates an experience for users that they’re directly manipulating the objects on the screen. Apps with a noticeable delay in user interaction (a hang) or movement on screen that appears to jump (a hitch), shatter that illusion. This leaves the user wondering whether the app is working correctly. To avoid hangs and hitches, keep the following rough thresholds in mind as you develop and test your app. 100 ms is the threshold for delays in direct user interaction. If a delay in user interaction becomes longer than 100 ms, it starts to become noticeable and causes a hang. A shorter delay is rarely noticeable. 5 ms is the threshold to achieve fluid motion on-screen. For fluid, uninterrupted motion, a new frame needs to be ready whenever the screen updates. On Apple devices, this can be as often as 120 times per second, or every 8.3 ms. Depending on system conditions and other work that your app performs, you might not have the full 8.3 ms to prepare your next screen update. If the work that your app needs to perform to update the screen is less than 5 ms, the update is usually ready in time. If it takes longer, you need to take a closer look at the specific devices you’re targeting and the display refresh rate your app needs to support. This article describes several best practices to help you avoid introducing hangs and hitches in your app, as well as multiple tools to help you detect and analyze these types of responsiveness issues.
- Beyond the basics of structured concurrency
It's all about the task tree: Find out how structured concurrency can help your apps manage automatic task cancellation, task priority propagation, and useful task-local value patterns. Learn how to manage resources in your app with useful patterns and the latest task group APIs. We'll show you how you can leverage the power of the task tree and task-local values to gain insight into distributed systems. Before watching, review the basics of Swift Concurrency and structured concurrency by checking out “Swift concurrency: Behind the scenes” and “Explore structured concurrency in Swift” from WWDC21.
- Write Swift macros
Discover how you can use Swift macros to make your codebase more expressive and easier to read. Code along as we explore how macros can help you avoid writing repetitive code and find out how to use them in your app. We'll share the building blocks of a macro, show you how to test it, and take you through how you can emit compilation errors from macros.
- Expand on Swift macros
Discover how Swift macros can help you reduce boilerplate in your codebase and adopt complex features more easily. Learn how macros can analyze code, emit rich compiler errors to guide developers towards correct usage, and generate new code that is automatically incorporated back into your project. We'll also take you through important concepts like macro roles, compiler plugins, and syntax trees.
- ObservableMacro.swift
Swift Observation and associated macros
- Do LLMs eliminate the need for programming languages?
We’ve learned a lot from building other compiler and programming language systems (e.g., Clang/C++, Swift, etc) over the last 20+ years. From that experience, we are building Mojo to:
- Be a fully compatible superset of Python, benefiting from its easy to read and understandable syntax and enabling its large community of developers to already know how to write Mojo!
- Support system programming features and hardware accelerators that extend the performance and reach of Python into new domains as we move into a new parallel-computing world.
- Be fully integrated with the existing Python ecosystem, extending and benefiting from all of the existing packages. We will also build seamless C and C++ interoperability to lift (and benefit from) work in those communities over time.
- Provide a new high-performance heterogeneous compiler and runtime implementation that benefits from state-of-the-art techniques.
As a consequence, we believe Mojo fits the perfect sweet spot for LLMs to generate and output highly scalable code, because it combines the human readability and usability of Python, but extends it with powerful lower-level systems features that enable it to scale across more hardware and drive the next set of the world’s applications and use cases.
We think LLMs will continue to unlock creativity and productivity across many languages, but we also believe Mojo will be well prepared to lift collaborative software development to the next level and bring programming into new frontiers.
- Explore SwiftUI animation
Explore SwiftUI's powerful animation capabilities and find out how these features work together to produce impressive visual effects. Learn how SwiftUI refreshes the rendering of a view, determines what to animate, interpolates values over time, and propagates context for the current transaction.
- Monitoring location changes with Core Location
Define boundaries and act on user location updates.
- Adopting live updates in Core Location
Simplify location delivery using asynchronous events in Swift.
- Managing model data in your app
Create connections between your app’s data model and views.
A SwiftUI app can display data that people can change using the app’s user interface (UI). To manage that data, an app creates a data model, which is a custom type that represents the data. A data model provides separation between the data and the views that interact with the data. This separation promotes modularity, improves testability, and helps make it easier to reason about how the app works.
Keeping the model data (that is, an instance of a data model) in sync with what appears on the screen can be challenging, especially when the data appears in multiple views of the UI at the same time.
SwiftUI helps keep your app’s UI up to date with changes made to the data thanks to Observation. With Observation, a view in SwiftUI can form dependencies on observable data models and update the UI when data changes.
- Demystify SwiftUI performance
Learn how you can build a mental model for performance in SwiftUI and write faster, more efficient code. We'll share some of the common causes behind performance issues and help you triage hangs and hitches in SwiftUI to create more responsive views in your app.
- Apple Design Resources — iOS 17 and iPadOS 17
Apple’s first official design kit for Figma contains a comprehensive set of components, views, system interfaces, text styles, color styles, materials, and layout guides. All the core ingredients you need to quickly create highly realistic iOS and iPadOS apps designs.
Some key features include:
- Comprehensive set of components, from Alerts to Widgets and everything in between
- Home Screen and Lock Screen widget templates
- Notification design templates
- Templates for tabbed apps, parent / child apps, split views, and sheets
- Full dynamic type chart with accessibility sizes
- Built in iOS system colors, materials, text styles and vibrancy effects
- Faster sorting algorithms discovered using deep reinforcement learning
Fundamental algorithms such as sorting or hashing are used trillions of times on any given day1. As demand for computation grows, it has become critical for these algorithms to be as performant as possible. Whereas remarkable progress has been achieved in the past2, making further improvements on the efficiency of these routines has proved challenging for both human scientists and computational approaches. Here we show how artificial intelligence can go beyond the current state of the art by discovering hitherto unknown routines. To realize this, we formulated the task of finding a better sorting routine as a single-player game. We then trained a new deep reinforcement learning agent, AlphaDev, to play this game. AlphaDev discovered small sorting algorithms from scratch that outperformed previously known human benchmarks. These algorithms have been integrated into the LLVM standard C++ sort library3. This change to this part of the sort library represents the replacement of a component with an algorithm that has been automatically discovered using reinforcement learning. We also present results in extra domains, showcasing the generality of the approach.
- AlphaDev discovers faster sorting algorithms
New algorithms will transform the foundations of computing
Digital society is driving increasing demand for computation, and energy use. For the last five decades, we relied on improvements in hardware to keep pace. But as microchips approach their physical limits, it’s critical to improve the code that runs on them to make computing more powerful and sustainable. This is especially important for the algorithms that make up the code running trillions of times a day.
In our paper published today in Nature, we introduce AlphaDev, an artificial intelligence (AI) system that uses reinforcement learning to discover enhanced computer science algorithms – surpassing those honed by scientists and engineers over decades.
AlphaDev uncovered a faster algorithm for sorting, a method for ordering data. Billions of people use these algorithms everyday without realising it. They underpin everything from ranking online search results and social posts to how data is processed on computers and phones. Generating better algorithms using AI will transform how we program computers and impact all aspects of our increasingly digital society.
By open sourcing our new sorting algorithms in the main C++ library, millions of developers and companies around the world now use it on AI applications across industries from cloud computing and online shopping to supply chain management. This is the first change to this part of the sorting library in over a decade and the first time an algorithm designed through reinforcement learning has been added to this library. We see this as an important stepping stone for using AI to optimise the world’s code, one algorithm at a time.
- toolbarTitleDisplayMode(_:)
Configures the toolbar title display mode for this view.
- ContentUnavailableView
An interface, consisting of a label and additional content, that you display when the content of your app is unavailable to users.
- XPCListener
A type that performs tasks for clients across process boundaries.
- ProximityReader
Read contactless physical and digital wallet cards using your iPhone.
The ProximityReader framework supports Tap to Pay on iPhone, which allows a person’s iPhone to act as a point-of-sale device without additional hardware. ProximityReader also supports the reading of loyalty cards from the Wallet app. Use this framework to initiate the payment process from your app.
The use of this framework requires you to coordinate with a participating payment service provider that is Level 3 certified. Contact your payment provider and work with them to set up a workflow for handling payments. When you’re ready, contact Apple and request the entitlement you need to integrate Tap to Pay on iPhone support into your app. For information on requesting this entitlement, see Setting up the entitlement for Tap to Pay on iPhone.
- DockKit
Interact with accessories that track subjects on camera as they move around.
- λ Lambda Calculus Calculator λ
- An Apple Library Primer
Apple’s library technology has a long and glorious history, dating all the way back to the origins of Unix. This does, however, mean that it can be a bit confusing to newcomers. This is my attempt to clarify some terminology.
- WWDC23
Highlights of new technologies introduced at WWDC23.
- Improving build efficiency with good coding practices
Shorten compile times by reducing the number of symbols your code exports and by giving the compiler the explicit information it needs.
- Improving the speed of incremental builds
Tell the Xcode build system about your project’s target-related dependencies, and reduce the compiler workload during each build cycle.
- Xcode Build settings reference
A detailed list of individual Xcode build settings that control or change the way a target is built.
- Configuring your project to use mergeable libraries
Use mergeable dynamic libraries to get app launch times similar to static linking in release builds, without losing dynamically linked build times in debug builds.
- How Swift Achieved Dynamic Linking Where Rust Couldn't
For those who don’t follow Swift’s development, ABI stability has been one of its most ambitious projects and possibly it’s defining feature, and it finally shipped in Swift 5. The result is something I find endlessly fascinating, because I think Swift has pushed the notion of ABI stability farther than any language without much compromise.
- Generalize APIs with parameter packs
Swift parameter packs are a powerful tool to expand what is possible in your generic code while also enabling you to simplify common generic patterns. We'll show you how to abstract over types as well as the number of arguments in generic code and simplify common generic patterns to avoid overloads. To get the most out of this session, we recommend first checking out “Embrace Swift generics" from WWDC22.
- Meet mergeable libraries
Discover how mergeable libraries combine the best parts of static and dynamic libraries to help improve your app's productivity and runtime performance. Learn how you can enable faster development while shipping the smallest app. We'll show you how to adopt mergeable libraries in Xcode 15 and share best practices for working with your code.
- Debug with structured logging
Discover the debug console in Xcode 15 and learn how you can improve your diagnostic experience through logging. Explore how you can navigate your logs easily and efficiently using advanced filtering and improved visualization. We'll also show you how to use the dwim-print command to evaluate expressions in your code while debugging.
- Xcode 15 Beta Release Notes
Xcode 15 beta includes SDKs for iOS 17, iPadOS 17, tvOS 17, watchOS 10, and macOS 14. The Xcode 15 beta release supports on-device debugging in iOS 12 and later, tvOS 12 and later, and watchOS 4 and later. Xcode 15 beta requires a Mac running macOS Ventura 13.3 or later.
- SwiftData
Write your model code declaratively to add managed persistence and automatic iCloud sync.
Combining Core Data’s proven persistence technology and Swift’s modern concurrency features, SwiftData enables you to add persistence to your app quickly, with minimal code and no external dependencies. Using modern language features like macros, SwiftData enables you to write code that is fast, efficient, and safe, enabling you to describe the entire model layer (or object graph) for your app. The framework handles storing the underlying model data, and optionally, syncing that data across multiple devices.
SwiftData has uses beyond persisting locally created content. For example, an app that fetches data from a remote web service might use SwiftData to implement a lightweight caching mechanism and provide limited offline functionality.
SwiftData is unintrusive by design and supplements your app’s existing model classes. Attach the Model macro to any model class to make it persistable. Customize the behavior of that model’s properties with the Attribute(_:renamingIdentifier:hashModifier:) and Relationship(::renamingIdentifier:inverse:hashModifier:) macros. Use the ModelContext class to insert, update, and delete instances of that model, and to write unsaved changes to disk.
To display models in a SwiftUI view, use the Query property wrapper and specify a predicate or fetch descriptor. SwiftData performs the fetch when the view appears, and tells SwiftUI about any subsequent changes to the fetched models so the view can accordingly. You can access the model context in any SwiftUI view using the modelContext environment value, and specify a particular model container or context for a view with the modelContainer(_:) and modelContext(_:) view modifiers.
As your app’s model layer evolves, SwiftData performs automatic migrations of the underlying model data so it remains in a consistent state. If the aggregate changes between two versions of the model layer exceed the capabilities of automatic migrations, use Schema and SchemaMigrationPlan to participate in those migrations and help them complete successfully.
- Backyard Birds: Building an app with SwiftData and widgets
Create an app with persistent data, interactive widgets, and an all new in-app purchase experience.
Backyard Birds offers a rich environment in which you can watch the birds that visit your backyard garden. You can monitor their water and food supply to ensure they always have fresh water and plenty to eat, or upgrade the game using in-app purchase to provide tastier food for the birds to eat.
The sample implements its data model using SwiftData for persistence, and integrates seamlessly with SwiftUI using the Observable protocol. The game’s widgets implement App Intents for interactive and configurable widgets. The in-app purchase experience uses the
ProductView
andSubscriptionStoreView
from StoreKit. You can access the source code for this sample on GitHub. - Observable
Defines and implements conformance of the Observable protocol.
- Observation
Make responsive apps that update the presentation when underlying data changes.
Observation provides a robust, type-safe, and performant implementation of the observer design pattern in Swift. This pattern allows an observable object to maintain a list of observers and notify them of specific or general state changes. This has the advantages of not directly coupling objects together and allowing implicit distribution of updates across potential multiple observers.
The Observation frameworks provides the following capabilities:
- Marking a type as observable
- Tracking changes within an instance of an observable type
- Observing and utilizing those changes elsewhere, such as in an app’s user interface
To declare a type as observable, attach the Observable macro to the type declaration. This macro declares and implements conformance to the Observable protocol to the type at compile time.
- Applying Macros
Use macros to generate repetitive code at compile time.
Swift macros help you avoid writing repetitive code in Swift by generating that part of your source code at compile time. Calling a macro is always additive: The macro adds new code alongside the code that you wrote, but never modifies or deletes code that’s already part of your project.
Many libraries provide macros, including the Swift standard library and many frameworks. You can also write your own macros.
Because macros generate Swift code, you use the same tools for development and debugging, regardless of whether your code uses macros
- OSAllocatedUnfairLock
A structure that creates an unfair lock.
Unfair locks are low-level locks that block efficiently on contention. They’re useful for protecting code that loads stored resources. However, it’s unsafe to use os_unfair_lock from Swift because it’s a value type and, therefore, doesn’t have a stable memory address. That means when you call os_unfair_lock_lock or os_unfair_lock_unlock and pass a lock object using the & operator, the system may lock or unlock the wrong object.
Instead, use OSAllocatedUnfairLock, which avoids that pitfall because it doesn’t function as a value type, despite being a structure. All copied instances of an OSAllocatedUnfairLock control the same underlying lock allocation.
- My Approach to Building Large Technical Projects
I'm not claiming that anything I say in this post is novel. It definitely shares various aspects of well-known software engineering or management practices. I'm just sharing the way I approach the larger technical work that I do and why I do it this way.
- Engineering Philosophy: Quality in Software
In software, quality isn’t just about whether the product “works” or is “performant”. Quality is about how easy it is to add new features, and how effectively new team members can understand and inherit the code. Do the abstractions you’ve introduced make sense within the domain? Is the complexity you’ve introduced through your abstractions actually justified by the problems it solves? Or have you merged groups of functionality together into massive core classes simply to remove the amount of repeated lines of code, regardless of whether those lines may need to diverge in the future? Despite our primal urges to DRY (don’t-repeat-yourself) up our code, repeated code is not itself a sin. If two pieces of repeated logic always change in tandem, then they should be unified. If two pieces of code change independently but happen right now to have the same logic, then they should not be unified.
The guiding principle of an abstraction should always be “Does this make the code easier to work with and understand?” The introduction of complexity is only ever justified if it solves for even greater complexity.
- SwiftUI Notes Before WWDC 2023
Here are some posts I’ve been collecting since iOS 16 and macOS 13. Hopefully they will soon be outdated.
- Network Path Monitoring
Apple released the Network framework in iOS 12, macOS 10.14. It includes a NWPathMonitor that is now the preferred way to monitor changes to network status. The three steps to monitor network changes:
- Create a NWPathMonitor.
- Call the start method of the path monitor passing a queue that will receive path change events.
- Receive path changes in the pathUpdateHandler.
- Avoiding SwiftUI’s AnyView
Let’s take a look at two core techniques that can help us avoid
AnyView
while still enabling us to work with multiple view types in very dynamic ways.
- Swift Evolution Dashboard
Anyone with a good idea can help shape the future features and direction of the language. To reach the best possible solution to a problem, we discuss and iterate on ideas in a public forum. Once a proposal is refined and approved, it becomes a release goal, and is tracked as a feature of an upcoming version of Swift.
To support this process, the Swift Evolution repository collects the goals for the upcoming major and minor releases (as defined by the core team) as well as proposals for changes to Swift. The Swift evolution process document details how ideas are proposed, discussed, reviewed, and eventually accepted into upcoming releases.
Below is a list of all the current and upcoming proposal reviews.
-
The Verse Calculus: a core calculus for functional logic programming
Functional logic languages have a rich literature, but it is tricky to give them a satisfying semantics. In this paper we describe the Verse calculus, VC, a new core calculus for functional logical programming. Our main contribution is to equip VC with a small-step rewrite semantics, so that we can reason about a VC program in the same way as one does with lambda calculus; that is, by applying successive rewrites to it.
-
Beginning in Swift 5.8 you can flexibly adopt upcoming Swift features using a new compiler flag and compilation condition. This post describes the problem upcoming feature flags solve, their benefits, and how to get started using them in your projects.
-
Defining Value Semantics for Swift
Requirements of Value Semantic Types
When we say “type X has value semantics,” we mean:
-
Each variable of type X has an independent notional value.
-
A language-level copy (e.g.,
let b = a
) of a variable of type X has an equivalent value. -
Given a local variable a of type
X
, safe code cannot observe the value ofa
except via an expression that usesa
. -
Given a variable a of type
X
, safe code cannot alter the value ofa
except by one of the following means applied toa
or to a property ofa
that reflects all or part ofa
's value.- assignment.
- invocation of a
mutating
method. - invocation of a
mutating
accessor of a property or subscript - passing the expression as an
inout
parameter.
-
Concurrent access to the values of distinct variables of type
X
cannot cause a data race.
-
-
Defunctionalization: Everybody Does It, Nobody Talks About It
All told, here’s the general procedure for defunctionalization:
- Collect all functions passed as an argument to the filter function.
- Create a data type, with one variant for each possible function, each with fields to store the free variables referenced by the corresponding function.
- Replace the invocation of the filter condition with an apply function, which determines what filter condition the data structure represents, and executes it.
-
Testing remote push notifications on iOS simulator in Xcode 14
To be able to send remote push notifications to an iOS simulator in Xcode 14, we have to be running macOS 13 on a computer with an Apple silicon or a T2 processor. In this setup, the simulator generates a unique registration token, which is specific to the combination of the simulator and the Mac hardware it’s running on.
The simulator supports the Apple Push Notification Service (APNS) Sandbox environment, which means that we have to connect to
api.sandbox.push.apple.com
to send a notification to the simulator. -
Using Layout protocol to align explicitly positioned views in SwiftUI
The new Layout protocol in iOS 16 lets us place views explicitly, and unlike the
position()
modifier, we can specify an anchor point when we call the place() method in placeSubviews(). -
You can use the GitHub API to trigger a webhook event called
repository_dispatch
when you want to trigger a workflow for activity that happens outside of GitHub. For more information, see "Repositories." -
An
xcframework
is a library distribution bundleMore precisely, an
xcframework
is a universal, binary, library distribution format. Let’s break that description down in reverse order.An
xcframework
is a library distribution format. Eachxcframework
holds exactly one library. A library is a precompiled collection of code that can be consumed by another project to create an executable (or app).An
xcframework
is a binary distribution format. That means it does not include source code in its distribution. Only built binaries and interface specifications (headers and/or Swift interface files) are included.An
xcframework
is a universal distribution format. That means it holds libraries and interfaces for different platforms as well as processor architectures in the same structure. A singlexcframework
can, for example, offer the same library for consumption for iOS, watchOS, and Mac projects using either Intel or ARM architectures.Finally, an
xcframework
is a bundle because it’s a directory with a well-defined content structure and file extension, and has anInfo.plist
file in its root. Examining itsInfo.plist
file shows that it has aCFBundlePackageType
ofXFWK
. -
Instant Pan Gesture Interactions
Turns out this is trickier than it seems, as
UIPanGestureRecognizer
has a small delay in startup where it requires you to move your finger before it recognizes the gesture starting. If you just touch your finger on the moving object, that’s not technically a “pan”, so it ignores you (makes sense), which means the object just keeps moving until you move enough to trigger a “pan”, the result of this is an interaction that doesn’t feel very responsive. -
Icarus provides first-class language support for Swift, C, C++, and Objective-C.
If you are Swift or C-family language developer, Icarus can provide you with first-class support for building client- and server-side applications and frameworks.
✨ Fun fact: This extension's debugging support was built entirely using Nova and Icarus. "Look ma, no Xcode!"
-
This is a list of changes to the Swift language that are frequently proposed but that are unlikely to be accepted. If you're interested in pursuing something in this space, please familiarize yourself with the discussions that we have already had. In order to bring one of these topics up, you'll be expected to add new information to the discussion, not just to say, "I really want this" or "this exists in some other language and I liked it there".
Additionally, proposals for out-of-scope changes will not be scheduled for review. The readme file identifies a list of priorities for the next major release of Swift, and the dashboard includes a list of changes that have been rejected after a formal review.
Several of the discussions below refer to "C family" languages. This is intended to mean the extended family of languages that resemble C at a syntactic level, such as C++, C#, Objective-C, Java, and Javascript. Swift embraces its C heritage. Where it deviates from other languages in the family, it does so because the feature was thought actively harmful (such as the pre/post-increment
++
) or to reduce needless clutter (such as;
or parentheses inif
statements). -
I agree it's not very relevant in this case, but I have measured this 🙂 adding Swift to an otherwise-empty (just
sleep()
s in main) C process on my Darwin system adds 128kB of total dirty memory, of which 16kB is heap memory coming from 28 additional allocations.This will vary depending on system libraries, symbol ordering, memory allocator, and other factors of course. My particular system is likely measuring a bit on the high side at the moment for unrelated reasons.
(edited to correct numbers slightly, I forgot I had edited my test program, and reverting the edits reduced it from 176kB to 128kB and from 37 allocations to 28)
-
Stop using floats
- BINARY DATA WAS NOT SUPPOSED TO HAVE DECIMAL PARTS
- YEARS OF COMPILER DEVELOPMENT yet NO REAL-WORLD USE FOUND for anything other than
char
andint
- Wanted to use decimal numbers anyway for a laugh? We had a tool for that: It was called FIXED-POINT ARITHMETIC
- 'x==x can be FALSE', 'j is a number', 'the sum of t and 7 is 0.30000000004'-statements dreamt up by the utterly Deranged
-
Tips and tricks for exploring a new codebase
When you join a new team, it’s tempting to keep your head down and study your new codebase. In your head, you might think that you’re expected to already know everything about the codebase even though you’re completely new to the project.
You might think that all patterns and practices in the project are industry standard and that you just haven’t worked in places as good as this one before.
All of these kinds of ideas exist in pretty much anybody’s head and they prevent you from properly learning and exploring a new codebase.
In this post, you have learned some tips about why human interaction is extremely important during your exploration phase. You also learned some useful tips for the more technical side of things to help you effectively tackle learning a new codebase.
Good luck on your next adventure into a new codebase!
-
Flexible Continuous Integration for iOS
At Airbnb, we run a comprehensive suite of continuous integration (CI) jobs before each iOS code change is merged. These jobs ensure that the main branch remains stable by executing critical developer workflows like building the iOS application and running tests. We also schedule jobs that perform periodic tasks like reporting metrics and uploading artifacts.
-
Attempting to connect a tvOS app to an iOS app with DeviceDiscoveryUI
It’s not necessarily a fair comparison as whilst you might expect them to be the same, the DeviceDiscoveryUI framework has a number of restrictions:
- It only works on tvOS (so you can’t communicate between an Apple Watch and an iPad like Apple Fitness can)
- It only works on Apple TV 4K (Apple Fitness can work with Apple TV HD)
- The tvOS app can only connect to one device at a time (i.e. you couldn’t make a game with this that used two iPhones as controllers)
- The tvOS app can only connect to other versions of your app that share the same bundle identifier (and are thus sold with Universal Purchase)
- This will not work on either the tvOS or iOS simulators. You must use physical devices.
-
SwiftFiddle is an online playground for creating, sharing, and embedding Swift fiddles (little Swift programs that run directly in your browser).
-
Automatically retrying an asynchronous Swift Task
Sometimes, we might want to automatically retry an asynchronous operation that failed, for example in order to work around temporary network problems, or to re-establish some form of connection.
But what if we wanted to implement something similar, but using Swift Concurrency instead? While Combine’s Publisher protocol includes the above retry operator as a built-in API, neither of Swift’s new concurrency APIs offer something similar (at least not at the time of writing), so we’ll have to get creative!
extension Task where Failure == Error {
@discardableResult
static func retrying(
priority: TaskPriority? = nil,
maxRetryCount: Int = 3,
retryDelay: TimeInterval = 1,
operation: @Sendable @escaping () async throws -> Success
) -> Task {
Task(priority: priority) {
for _ in 0..<maxRetryCount {
do {
return try await operation()
} catch {
let oneSecond = TimeInterval(1_000_000_000)
let delay = UInt64(oneSecond * retryDelay)
try await Task<Never, Never>.sleep(nanoseconds: delay)
continue
}
}
try Task<Never, Never>.checkCancellation()
return try await operation()
}
}
}
- Swift Validated
A result type that accumulates multiple errors.
- Mojo Dojo
Learning Resources for Mojo 🔥
- Using Swift’s Types as Domain-Specific Languages
I want to show you, how we can use Swift’s Types to create modules — Datatypes, UseCases, Features — that will be controlled through a vocabulary defined by their Domain Specific Languages (DSL).
As these vocabularies are finite sets, this kind of coding has proven to enable coding of even complex domains in simple fashions and in very little time — think: hours where conventional coding needs weeks.
- Interesting how many Apple-platform UI design, wireframing, prototyping, animation and/or code generation tools that exists these days:
- Sketch
- PaintCode
- DetailsPro
- Drama
- Principle
- Origami Studio
- Judo
- Kolibri
- Flinto
- OmniGraffle
- Keynote
- Tumult Hype
- Play
- The Ultimate Domain Language: Declarative Swift
Exploring declarative domain paradigm
- HIG Layout
Using a consistent layout that adapts to various contexts makes your experience more approachable and helps people enjoy their favorite apps and games on all their devices.
- SwiftUI Layout fundamentals
Arrange views inside built-in layout containers like stacks and grids.
Use layout containers to arrange the elements of your user interface. Stacks and grids update and adjust the positions of the subviews they contain in response to changes in content or interface dimensions. You can nest layout containers inside other layout containers to any depth to achieve complex layout effects.
To finetune the position, alignment, and other elements of a layout that you build with layout container views, see Layout adjustments. To define custom layout containers, see Custom layout. For design guidance, see Layout in the Human Interface Guidelines.
- overlay(alignment:content:)
Layers the views that you specify in front of this view.
- The power of overlays in SwiftUI
An overlay is a view drawing on top of another view. And today, we will talk about two interesting use cases of using overlays in SwiftUI. One of them allows us to keep the structural identity of the view, and another one becomes very handy whenever you build custom navigation transitions.
- Context SDK
Context SDK leverages machine learning to make optimized suggestions when to upsell an in-app purchase, what type of ad and dynamic copy to display, or predict what a user is about to do in your app, and dynamically change the product flows to best fit their current situation.
- Connecting the world one conversation at a time
Byrdhouse is a multilingual video conferencing application that helps global teams to communicate and collaborate across 100+ languages with AI-powered real-time translation and meeting notes.
- Mojo🔥 programming manual
Mojo is a programming language that is as easy to use as Python but with the performance of C++ and Rust. Furthermore, Mojo provides the ability to leverage the entire Python library ecosystem.
Mojo achieves this feat by utilizing next-generation compiler technologies with integrated caching, multithreading, and cloud distribution technologies. Furthermore, Mojo’s autotuning and compile-time meta-programming features allow you to write code that is portable to even the most exotic hardware.
More importantly, Mojo allows you to leverage the entire Python ecosystem so you can continue to use tools you are familiar with. Mojo is designed to become a superset of Python over time by preserving Python’s dynamic features while adding new primitives for systems programming. These new system programming primitives will allow Mojo developers to build high-performance libraries that currently require C, C++, Rust, CUDA, and other accelerator systems. By bringing together the best of dynamic languages and systems languages, we hope to provide a unified programming model that works across levels of abstraction, is friendly for novice programmers, and scales across many use cases from accelerators through to application programming and scripting.
This document is an introduction to the Mojo programming language, fit for consumption by Mojo programmers. It assumes knowledge of Python and systems programming concepts but it does not expect the reader to be a compiler nerd. At the moment, Mojo is still a work in progress and the documentation is targeted to developers with systems programming experience. As the language grows and becomes more broadly available, we intend for it to be friendly and accessible to everyone, including beginner programmers. It’s just not there today.
- Mojo 🔥 — a new programming language for all AI developers.
Mojo combines the usability of Python with the performance of C, unlocking unparalleled programmability of AI hardware and extensibility of AI models.
- Modular Performance Dashboard
The Performance Dashboard is where you can compare the performance of standard industry models on Modular’s infrastructure.
- Supporting passkeys
Eliminate passwords for your users when they sign in to apps and websites.
Passkeys use iCloud Keychain public key credentials, eliminating the need for passwords. Instead, they rely on biometric identification, such as Touch ID and Face ID in iOS, or a specific confirmation in macOS for generating and authenticating accounts.
As the authenticator, your Apple device generates a unique public-private key pair for every account it creates on a service. The authenticator retains the private key and shares its public key with the server, known as the relying party.
- Apple and Google lead initiative for an industry specification to address unwanted tracking
Location-tracking devices help users find personal items like their keys, purse, luggage, and more through crowdsourced finding networks. However, they can also be misused for unwanted tracking of individuals.
Today Apple and Google jointly submitted a proposed industry specification to help combat the misuse of Bluetooth location-tracking devices for unwanted tracking. The first-of-its-kind specification will allow Bluetooth location-tracking devices to be compatible with unauthorized tracking detection and alerts across iOS and Android platforms. Samsung, Tile, Chipolo, eufy Security, and Pebblebee have expressed support for the draft specification, which offers best practices and instructions for manufacturers, should they choose to build these capabilities into their products.
- DocC
Produce rich API reference documentation and interactive tutorials for your app, framework, or package.
- DocC API Documentation
Teach developers your Swift and Objective-C APIs through reference documentation you create from comments in Swift source code, Objective-C header files, and documentation extension files.
- DocC Interactive Tutorials
Teach developers your Swift and Objective-C APIs through step-by-step, interactive content.
- Platform as a Product
The core premise of “Platform as a Product” is to make explicit the need for a platform (low variability) to exist as a separate system from the customer-facing products (valuable variation**), and requires a long-lived platform team, practices, and budget to support it. Just to dive into this briefly: a platform is designed similarly to the manufacturing production line below — we want a platform to provide consistency and reliability (low variability). Indeed, it’s the consistency and reliability provided by a platform that enables a customer-facing product team to deliver products demonstrating high variation — which means we can rapidly deliver and test new features and changes.
- UIViewController.ViewLoading
A property wrapper that loads the view controller’s view before accessing the property.
Use this property wrapper on view controller properties that can be
nil
before the view controller’s view loads. Wrapping view controller properties this way eliminates crashes that can occur from implicitly defining properties asOptional
, and then referencing them before the view controller finishes loading. - SCRAPSCRIPT
Scrapscript is best understood through a few perspectives:
- “it’s JSON with types and functions and hashed references”
- “it’s tiny Haskell with extreme syntactic consistency”
- “it’s a language with a weird IPFS thing"
Scrapscript solves the software sharability problem.
Modern software breaks at boundaries. APIs diverge, packages crumble, configs ossify, serialization corrupts, git tangles, dependencies break, documentation dies, vulnerabilities surface, etc.
To make software safe and sharable, scrapscript combines existing wisdom in new ways:
- all expressions are content-addressible “scraps”
- all programs are data
- all programs are “platformed”
- Risk-storming
- Draw some software architecture diagrams
- Identify the risks individually
- Converge the risks on the diagrams
- Review and summarise the risks
- Architecture Modernization [Miro]
- openAI Unison Share
- The Hackett Programming Language
Hackett is a statically typed, pure, lazy, functional programming language in the Racket language ecosystem. Despite significant differences from #lang racket, Hackett shares its S-expression syntax and powerful, hygienic macro system. Unlike Typed Racket, Hackett is not gradually typed—it is designed with typed programs in mind, and it does not have any dynamically-typed counterpart.
- Skip typing your login credentials manually with Xcode breakpoints
With Xcode breakpoints you can set up your login credentials during development so you don't have to type them manually every time you run your app.
- SetAlgebra
You use types that conform to the
SetAlgebra
protocol when you need efficient membership tests or mathematical set operations such as intersection, union, and subtraction. In the standard library, you can use theSet
type with elements of any hashable type, or you can easily create bit masks withSetAlgebra
conformance using theOptionSet
protocol. See those types for more information. - Byte Code Based Value Witnesses
Rather than generating code for the types, we propose instead to compute a compile time type layout, then create a runtime function that interprets the type layout, computing alignments and addresses at runtime to copy or free them.
- A list of programming playgrounds
- Reimagining the microservice: an early preview
There's no packaging step, no building containers, or anything like that. You just call a function in the Unison Cloud API to deploy the service. Unison automatically uploads your function and all of its dependencies to Unison Cloud, caching them on the server.
- Making dependencies available to Xcode Cloud
Review dependencies and make them available to Xcode Cloud before you configure your project to use Xcode Cloud.
- Swift AST Explorer
- Compose Multiplatform
Develop stunning shared UIs for Android, iOS, desktop, and web.
- Allow Generic Types to Abstract Over Packs
In the generic parameter list of a generic type, the
each
keyword declares a generic parameter pack, just like it does in the generic parameter list of a generic function. The types of stored properties can contain pack expansion types, as inlet seq
andvar iter
above. - Shortcuts File Format Documentation
- Deep Into Shortcuts
- Observation
Making responsive apps often requires the ability to update the presentation when underlying data changes. The observer pattern allows a subject to maintain a list of observers and notify them of specific or general state changes. This has the advantages of not directly coupling objects together and allowing implicit distribution of updates across potential multiple observers. An observable object needs no specific information about its observers.
This design pattern is a well-traveled path by many languages, and Swift has an opportunity to provide a robust, type-safe, and performant implementation. This proposal defines what an observable reference is, what an observer needs to conform to, and the connection between a type and its observers.
- Creating performant scrollable stacks
Display large numbers of repeated views efficiently with scroll views, stack views, and lazy stacks.
Your apps often need to display more data within a container view than there is space for on a device’s screen. Horizontal and vertical stacks are a good solution for repeating views or groups of views, but they don’t have a built-in mechanism for scrolling. You can add scrolling by wrapping stacks inside a ScrollView, and switch to lazy stacks as performance issues arise.
- Height
Manage projects across product and support
Real-time tasks, chat, and powerful customization to get everyone on the same page.
- Technical dimensions of programming systems
Programming is done in a stateful environment, by interacting with a system through a graphical user interface. The stateful, interactive and graphical environment is more important than the programming language(s) used through it. Yet, most research focuses on comparing and studying programming languages and only little has been said about programming systems.
Technical dimensions is a framework that captures the characteristics of programming systems. It makes it possible to compare programming systems, better understand them, and to find interesting new points in the design space of programming systems. We created technical dimensions to help designers of programming systems to evaluate, compare and guide their work and, ultimately, stand on the shoulders of giants.
- 'Modules Matter Most' for the Masses
Understanding real modules is worthwhile even if you never intend to work in a language that has them. Modules are fundamental, and so much of what is done in other languages, from build configurations to dependency injection to the Adapter pattern, are in large part an attempted encoding of things easily expressed with modules.
- Why Programmers Should(n't) Learn Theory
So, here’s the overall tally of fields and their usefulness in terms of lessons for software design:
- Type theory: Very useful
- Program Analysis: Not useful, other than the definition of “abstraction.”
- Program Synthesis: Old-school derivational synthesis is useful; modern approaches less so.
- Formal Verification: Mechanized verification is very useful; automated not so much.
- Category theory: Not useful, except a small subset which requires no category theory to explain.
So, we have a win for type theory, a win for the part of verification that intersects type theory (by dealing with types so fancy that they become theorems), and a wash for everything else. So, go type theory, I guess.
In conclusion, you can improve your software engineering skills a lot by studying theoretical topics. But most of the benefit comes from the disciplines that study how programs are constructed, not those that focus on how to build tools.
- Tramline
Release apps without drowning in process
Codify your app's release cycle, distribute builds with increased confidence, and give visibility to the entire organization
- Interesting Swift Snippet to create JSON
let neverJSON = Data(#"{"no":"never"}"#.utf8)
- Deque
A collection implementing a double-ended queue.
- CaseDetectionMacro.swift
- swift-macro-examples
- Imperative Programming with Poly
Traditionally, side-effects in functional programming are handled using monads. However, David Spivak and I are attempting a different approach.
In this post, we are going to discuss turing machines via a particular construction in Poly, and then show the general framework we have developed. Not all of the puzzle pieces are there yet in order to make this a fully-fledged theory of imperative programming, but we have to walk before we can run.
- When Matched Geometry Effect Doesn't Work
The Declaration Order Matters
- How to Set Up an Edit-Build-Test-Debug Loop
This document describes how to set up a development loop for people interested in contributing to Swift.
- swift-inspect
swift-inspect
is a debugging tool which allows you to inspect a live Swift process to gain insight into the runtime interactions of the application.swift-inspect
uses the reflection APIs to introspect the live process. It relies on the swift remote mirror library to remotely reconstruct data types. - LocalTestingDistributedActorSystem
A
DistributedActorSystem
designed for local only testing. - How to be a -10x Engineer
+10x engineers may be mythical, but -10x engineers exist.
To become a -10x engineer, simply waste 400 engineering hours per week.
- higher-free-macro
A macro that creates a (naive) Free Monad type based on a user-supplied Functor. It uses the traits from the "higher" crate. This macro is a port of the Control.Monad.Free part of the "free" Haskell package by Edward Kmett.
- The Streaming Book
A free and chart-filled mini-book on where we are in the Streaming Wars, have been, and will go. From the national and international best-selling author, and former streaming executive,
Matthew Ball
. - Reliably testing code that adopts Swift Concurrency?
Just wanted to share an update, as we've continued to write more and more tests for code that uses Swift concurrency. Introducing Swift concurrency to a feature continues to be the biggest cause of test flakiness in our experience, but we have managed to reduce flakiness dramatically by cribbing some helpers from swift-async-algorithms, in particular, a "C async support" module, which exposes a global hook override for task enqueuing, which we use to redirect everything to the main, serial executor:
import _CAsyncSupport
@_spi(Internals) public func _withMainSerialExecutor<T>(
@_implicitSelfCapture operation: () async throws -> T
) async rethrows -> T {
let hook = swift_task_enqueueGlobal_hook
defer { swift_task_enqueueGlobal_hook = hook }
swift_task_enqueueGlobal_hook = { job, original in
MainActor.shared.enqueue(unsafeBitCast(job, to: UnownedJob.self))
}
return try await operation()
}
> Whenever we have a flakey continuous integration failure, we wrap the test with this helper and don't typically have a concurrency-based problem with that test again. As a bonus, the test runs more quickly.
>
> The solution is far from perfect, but has saved us from a ton of pain, and we think it basically makes async code behave more like Combine code (_i.e._ well-defined "subscription" order), and hence becomes a lot more reliable to test.
>
> I believe it will probably only work for code that does not use custom executors, but that should be the case for most folks right now. We also haven't tried to include this code in library/application code yet, but if Swift doesn't provide a public solution to the problem, we'll likely look into extracting this helper into its own package, which should make it easier to drop into a project.
- Using foregroundColor(), foregroundStyle() or tint() to set text color in SwiftUI
SwiftUI has a few different modifiers that can change the color of text, such as foregroundColor(_:), foregroundStyle(_:), and tint(_:). They provide different functionality, but sometimes overlap and it can be hard to know for sure which modifier to choose. In this post we will go over some common use cases for all three of the modifiers and see which one suits best for what purpose.
- How the relative size modifier interacts with stack views
And what it can teach us about SwiftUI’s stack layout algorithm
I have one more thing to say on the relative sizing view modifier from my previous post, Working with percentages in SwiftUI layout. I’m assuming you’ve read that article. The following is good to know if you want to use the modifier in your own code, but I hope you’ll also learn some general tidbits about SwiftUI’s layout algorithm for HStacks and VStacks.
- A Collection of Mobile App Store Quirks
As mobile developers, we face unique challenges when it comes to releasing and managing updates for our apps across different app stores. One of the primary reasons for this difficulty is the scattered and insufficient documentation available, which lacks the necessary level of detail and nuance to provide a clear understanding of the process.
Additionally, the interfaces and tools provided by these stores for managing releases are often opaque and and don't offer much insight into how things work behind the scenes, which further complicates the process.
This reference is a compilation of answers for common and rare situations in an attempt to increase transparency. It is compiled from experience, developer forums, Stack Overflow, and various other sources of developer documentation. We hope contributions from other developers will grow this resource further.
- Enabling Upcoming Swift Language Features
By adding the new compiler flag
-enable-upcoming-feature
and appending the feature flags we would like to enable to the “Swift Compiler - Custom Flags” section in Xcode, the compiler will enable the selected features for us. For example, if we wanted to enable existential any and strict concurrency checking, we could provide the compiler with this flag:-enable-upcoming-feature ExistentialAny StrictConcurrency
.StrictConcurrency
here is equivalent to-warn-concurrency
, as it exists in Swift 5.7 and earlier. - Working with percentages in SwiftUI layout
SwiftUI’s layout primitives generally don’t provide relative sizing options, e.g. “make this view 50 % of the width of its container”. Let’s build our own!
- AVMetadataObject.ObjectType
- Constants that identify metadata object types.
- Verse Language Reference
See the design goals of the Verse programming language and its features. Use this section as a reference.
Verse is a programming language developed by Epic Games that you can use to create your own gameplay in Unreal Editor for Fortnite, including customizing your devices for Fortnite Creative.
- Learn the Basics of Writing Code in Verse
A short course to introduce Verse to people with no programming experience whatsoever. No. Programming. Experience. Whatsoever. Seriously.
- a[crop]alypse
Screenshot recovery utility
- Migrating to new navigation types
Improve navigation behavior in your app by replacing navigation views with navigation stacks and navigation split views.
If your app has a minimum deployment target of iOS 16, iPadOS 16, macOS 13, tvOS 16, or watchOS 9, or later, transition away from using NavigationView. In its place, use NavigationStack and NavigationSplitView instances. How you use these depends on whether you perform navigation in one column or across multiple columns. With these newer containers, you get better control over view presentation, container configuration, and programmatic navigation.
- XCTContext
A proxy for the current testing context.
XCTContext
provides a way for activities (XCTActivity) to run against the current testing context, either directly in a test case or in custom testing utilities. You can break up long test methods in UI tests or integration tests into activities to reuse, and to simplify results in the Xcode test reports. Use runActivity(named:block:) to run a block of code as a named substep in a test. For more information, see Grouping Tests into Substeps with Activities. - Grouping Tests into Substeps with Activities
Simplify test reports by creating activities that organize substeps within complex test methods.
- On trust in software development
There are many good reasons to be critical of code reviews, pull requests, and other processes that seem to slow things down. The lack of trust in co-workers is, however, not one of them.
You can easily be swayed by that argument because it touches something deep in our psyche. We want to be trusted, and we want to trust our colleagues. We want to belong.
The argument is visceral, but it misrepresents the motivation for process. We don't review code because we believe that all co-workers are really North Korean agents looking to sneak in security breaches if we look away.
We look at each other's work because it's human to make mistakes. If we can't all be in the same office at the same time, fast but asynchronous reviews also work.
- Using Swift’s Type System To Model Behaviour
Create fully immutable types for your domain using Swift
- Spelunking Apple’s Open Source
This resource is useful primarily to developers, but may also interest curious technophiles who want to take a peek “behind the curtain” to see how much of the magic just beneath our fingertips is made.
- Blendmode trick: SwiftUI reverse mask
SwiftUI has the
mask(alignment:_:)
modifier that masks the view using the alpha channel of the given view. The reverse function is not part of SwiftUI though, but can easely be made using a blendmode trick.
extension View {
@inlinable
public func reverseMask<Mask: View>(alignment: Alignment = .center, @ViewBuilder _ mask: () -> Mask) -> some View {
self.mask(
Rectangle()
.overlay(alignment: alignment) {
mask()
.blendMode(.destinationOut)
}
)
}
}
-
The role of knowledge-based resources in Agile Software Development contexts
The software value chain is knowledge-based since it is highly dependant on people. Consequently, a lack of practice in managing knowledge as a resource may jeopardise its application in software development. Knowledge-Based Resources (KBRs) relate to employees’ intangible knowledge that is deemed to be valuable to a company’s competitive advantage. In this study, we apply a grounded theory approach to examine the role of KBRs in Agile Software Development (ASD). To this aim, we collected data from 18 practitioners from five companies. We develop the Knowledge-Push theory, which explains how KBRs boost the need for change in ASD. Our results show that the practitioners who participated in the study utilise, as primary strategies, task planning, resource management, and social collaboration. These strategies are implemented through the team environment and settings and incorporate an ability to codify and transmit knowledge. However, this process of codification is non-systematic, which consequently introduces inefficiency in the domain of knowledge resource utilisation, resulting in potential knowledge waste. This inefficiency can generate negative implications for software development, including meaningless searches in databases, frustration because of recurrent problems, the unnecessary redesign of solutions, and a lack of awareness of knowledge sources.
-
A request that detects barcodes in an image.
-
The First ACM SIGPLAN Workshop on Functional Software Architecture — FP in the Large
“Functional Software Architecture” refers to methods of construction and structure of large and long-lived software projects that are implemented in functional languages and released to real users, typically in industry.
The goals for the workshop are:
- To assemble a community interested in software architecture techniques and technologies specific to functional programming;
- To identify, categorize, and document topics relevant to the field of functional software architecture;
- To connect the functional programming community to the software architecture community to cross-pollinate between the two.
-
A Glossary of Functional Programming
I’ve taught functional programming for years now, each time experimenting with different ways of teaching core concepts. Over time, I’ve collected and converged on simple (but reasonably precise) pedagogical definitions for a range of functional concepts.
-
Tries are prefix trees, where the key is usually a String.
A trie is a special case of a tree where characters are stored at each node, and a path down the tree represents a word.
-
Reverse Engineering the Apple MultiPeer Connectivity Framework
-
Building Large-Scale Apps with SwiftUI: A Guide to Modular Architecture
Software architecture is always a topic for hot debate, specially when there are so many different choices. For the last 8-12 months, I have been experimenting with MV pattern to build client/server apps and wrote about it in my original article SwiftUI Architecture - A Complete Guide to MV Pattern Approach. In this article, I will discuss how MV pattern can be applied to build large scale client/server applications.
-
Release your apps that aren’t suited for public distribution as unlisted on the App Store, discoverable only with a direct link. Unlisted apps don’t appear in any App Store categories, recommendations, charts, search results, or other listings. In addition, they can be accessed through Apple Business Manager and Apple School Manager. Apps for partner sales tools, employee resources, or research studies are examples of good candidates for unlisted distribution.
Distribute your app to:
- Limited audiences (such as part-time employees, franchisees, partners, business affiliates, higher-education students, or conference attendees) through a standard link that’s usable on the App Store and Apple School Manager or Apple Business Manager.
- Employee-owned devices that aren’t eligible to be managed through Apple School Manager or Apple Business Manager.
- Managed and unmanaged devices.
- All regions that are supported by the App Store.
-
Pitch: Dependent Types & Universes
Next year will be the 10-year anniversary of Swift. Moore's Law means we get to have nicer things in the future, like Apple Silicon and the Internet of Things. Yet the more powerful and ubiquitous computing devices become, the more damage can result if our software malfunctions.
Therefore we must continue to improve Swift along its primary goals of simplicity and safety. So lets bring over some new features from the cutting edge of computer science.
-
This is the app previously known as watchGPT. Quickly get answers to your questions or generate longer messages without typing.
We are excited to introduce Petey your Al assistant app for the Apple Watch! With this app, you can now interact with the famous GPT model right from your wrist.
-
A type that can convert itself into and out of an external representation with the help of a configuration that handles encoding contained types.
CodableWithConfiguration is a type alias for the EncodableWithConfiguration and DecodableWithConfiguration protocols. Use this protocol to support codability in a type that can’t conform to Codable by itself, but can do so with additional statically-defined configuration provided by a CodableConfiguration instance.
AttributedString uses this approach to allow an instance to contain arbitrary attributes, including frameworks outside of Foundation or the platform SDK. It does this by including one or more AttributeScope instances, a type that conforms to EncodingConfigurationProviding and DecodingConfigurationProviding. An attribute scope like AttributeScopes.SwiftUIAttributes defines attribute keys, and conforms to
AttributeScope
to provide configuration instances that know the AttributedStringKey types and their associated Value types. With this type information, anAttributedString
can encode all of its attributes, even from frameworks other than Foundation. -
Compiling Swift generics, Part I
The target audience is Swift compiler developers: if you've previously encountered
GenericSignatures
,GenericEnvironments
,SubstitutionMaps
andProtocolConformances
and found them slightly mysterious, this is definitely for you. You might also want to take a look if you're interested in programming language design or type systems in general. -
A monad is a lax 2-functor from the terminal 2-category 1 to Cat.
-
const wow: ("hello" | "world") | (string & {})
//wow
is of type"hello"
or"world"
orstring
.This weird-looking intersection of
string & {}
makes it so that the specific strings"hello"
and"world"
are distinguished fromstring
as a whole type. -
How to Change the Background Color of Navigation Bars in all iOS versions?
The SwiftUI Navigation Bar has no easy way to change its color, that being iOS 13 or iOS 16 I feel that is something clanky and should be easier. The good news is that we have some workarounds that work pretty well.
-
Visualizing Remote computations
This project contains a version of Remote.pure.run that is capable of programmatically producing mermaid diagrams to visualize the forked and awaited tasks in a Remote computation.
-
En dash, em dash and hyphen; what’s the difference? (also ndash and mdash, or n-dash and m-dash)
The hyphen, em dash and en dash are everywhere, but most of us don’t know when or why to use them – and different writers use the dashes in different ways. Let’s figure this out!
-
A guide to getting you on the IndieWeb
- Become a citizen of the IndieWeb
- Publishing on the IndieWeb
- Federating IndieWeb Conversations
-
Any distributed software system can be built by combining these 9 message processing patterns.
-
A language is sound if it doesn't accept programs that it shouldn't.
This deserves a longer post.
A language is sound if it doesn't accept programs that it shouldn't. "Shouldn't" is doing a lot of work there, though: it's an inherently open concept, reliant on an external semantic model. In programming languages, we generally say a program shouldn't be accepted if it "won't work", but our definition for "work" is that individual operations will behave like they're expected to, not that the program as a whole will do what the programmer meant for it to do. The latter definition, of course, can't be applied without pulling the user's intent into the semantic model, and any sort of bug in the program (or flaw in the user's understanding) would become an "unsoundness" in the language. (For example, if I wrote a Fibonacci-style function that started with 3,4,..., the language would be unsound if I meant it to be the standard Fibonacci sequence.) In the more standard PL approach, the language designer just has to rigorously define how individual operations are supposed to work.
One way to do that is to give well-defined semantics to all possible combinations of operands, even ones that don't a priori make much sense. This is common in dynamically-typed languages; for example, JavaScript's subscript operator is well-defined even if you use it on an integer. In statically-typed languages, we usually rule out a lot of those cases by defining static preconditions on operations. For example, in Swift, the subscript syntax requires the base operand to statically have a
subscript
member, and then the dynamic semantics impose a precondition that the base value actually has the type it was type-checked to have. In that world, the language is formally sound as long as it's correctly enforcing that those static preconditions on individual operations can't be violated.Sometimes we do use "soundness" in a slightly less formal sense: we argue about how users expect basic operations to work. In this informal sense, a language can be unsound if it violates those user expectations even if dynamically everything remains well-defined. For example, Java has covariant object arrays: you can implicitly convert a
String[]
toObject[]
, but assignments into the result will fail with an exception if they aren't dynamicallyString
s. This is not formally unsound in Java because this aspect of the well-typedness of the array assignment syntax is not a static precondition; it's a well-defined dynamic check. Nonetheless, it is very arguably unsound behavior under a higher-level understanding of how assigning into an array element ought to work, because a bunch of things that the language accepts implicitly and without complaint can be combined to dynamically fail with a type error.But I have a hard time accepting that that could ever apply to dynamic cast. Dynamic casts are an explicit syntax whose entire purpose is to dynamically check whether a value has a particular type. The possibility that that can fail when values don't have that type is inherent to the operation.
-
Modern iOS Navigation Patterns
This page collects all the familiar navigation patterns for structuring iOS apps, like drill-downs, modals, pyramids, sequences, and more! Think of it as an unofficial bonus chapter for Apple’s Human Interface Guidelines, written by someone who cares deeply about well-crafted user interfaces.
-
Introducing Swift Certificates and Swift ASN.1
I’m excited to announce two new open source Swift packages: swift-certificates and swift-asn1. Together, these libraries provide developers a faster and safer implementation of X.509 certificates, a critical technology that powers the security of TLS.
-
The AI product manager that writes your Jira tickets
JiraPT-3 is your team's newest AI-powered Product Manager that uses GPT-3 to write user stories and epics. This is the Chrome extension for Product Managers who want to 10X their output 🤖 or for Developers who want to automate PMs away 🤭
- When prompted with user story “As a , I want , so that I can ___”, JiraPT-3 will create:
- A fully-formed description containing context on the user and their goal
- A clearly-defined set of Acceptance Criteria that outlines the workflow to achieve the user’s goal.
-
GitHub Blocks — Reimagine Repositories
Extend your codebase with custom, interactive blocks.
Build rich documentation, enhance your workflows, and bring your repository to life.
-
Publishing a Swift package with Xcode
Publish your Swift package privately, or share it globally with other developers.
Making your Swift packages available online enables you to use the support for Swift package dependencies in Xcode. By publishing your Swift packages to private Git repositories, you can manage and integrate internal dependencies across your projects, allowing you to reduce duplicate code and promote maintainability. Publish your packages publicly, and share your code with developers around the world. To get started, you just need a Swift package and an account with a provider of hosted Git repositories.
-
Edit images and video with async / await in Swift, powered by Metal.
The main value type in AsyncGraphics is a Graphic. It’s like an image, but with various various methods for applying effects and some static methods for creating visuals.
AsyncGraphics also has another value type called Graphic3D. It’s a 3d image, a volume of voxels.
-
The words you choose within your app are an essential part of its user experience.
Whether you're building an onboarding experience, writing an alert, or describing an image for accessibility, designing through the lens of language will help people get the most from your app or game.
-
The purity of Haskell allows for mathematical reasoning about programs. This not only makes it possible to be more confident in the correctness of our programs but can be used in order to optimize code as well. In fact, the primary Haskell compiler, GHC, uses these guarantees in order to optimize programs. The restrictions imposed by purity turn into properties that programmers and compilers alike may use to their advantage.
-
SwiftUI views versus modifiers
While we could attempt to solve that clarity problem with more verbose API naming, the core issue would still remain — that the modifier-based version doesn’t properly show what the resulting view hierarchy will be in this case. So, in situations like the one above, when we’re wrapping multiple siblings within a parent container, opting for a view-based solution will often give us a much clearer end result.
On the flip side, if all that we’re doing is applying a set of styles to a single view, then implementing that as either a “modifier-like” extension, or using a proper
ViewModifier
type, will most often be the way to go. And for everything in between — such as our earlier “featured label” example — it all really comes down to code style and personal preference as to which solution will be the best fit for each given project. -
Improving code assessment by organizing tests into test plans
Control the information you receive from your tests at different stages in the software engineering process by creating and configuring test plans.
-
Design and code, united at last
Judo is a design and build tool for SwiftUI apps that writes production-ready code for you while you’re designing. Eliminate back-and-forth with developers and free them from unrewarding grunt work.
-
How to fix iCloud Safari tabs syncing bug
- On your Mac, backup your Safari data — bookmarks, etc. Just in case.
- Completely quit Safari on all devices.
- Disable Safari syncing in iCloud settings on all devices. Choose the option to delete the data from the device on iOS, but keep the data on your Mac.
- Launch Safari on all devices. Bookmarks, etc. should be gone on iOS.
- Completely quit Safari on all devices, again.
- Reboot all devices.
- Re-enable Safari syncing in iCloud settings on all devices.
- Launch Safari on your Mac, so it can sync the initial data.
- Launch Safari on all iOS devices.
-
SwiftUI: The difference between List and LazyVStack
The gist is that LazyVStack is just lazy, but this is not even close to the UICollectionView / UITableView, List (which is still backed by a UIKit UICollectionView). Any of those reuse / cycle views are you need them. LazyVStack just grow in size, forever. So the longer it is, the more you scroll, the slower it get!
-
Instead of having separate routes for each API endpoint, we could just have a single API endpoint that takes in a huge enum and switches on that. We can then share that enum with the client and they’d automatically be in sync.
-
In my opinion git submodule is never the right answer. Often, git submodule is the worst answer and any of the following would be better.
Use git subtree
git subtree solves many of the same problems as git submodule, but it does not violate the git data model.
-
Use a state object as the single source of truth for a reference type that you store in a view hierarchy. Create a state object in an App, Scene, or View by applying the
@StateObject
attribute to a property declaration and providing an initial value that conforms to the ObservableObject protocol. Declare state objects as private to prevent setting them from a memberwise initializer, which can conflict with the storage management that SwiftUI provides.SwiftUI creates a new instance of the model object only once during the lifetime of the container that declares the state object. For example, SwiftUI doesn’t create a new instance if a view’s inputs change, but does create a new instance if the identity of a view changes. When published properties of the observable object change, SwiftUI updates any view that depends on those properties, like the Text view in the above example.
Note: If you need to store a value type, like a structure, string, or integer, use the State property wrapper instead.
-
Lightweight Formal Methods: String Diagrams
And, most importantly, the whole team can collaborate in on the design. In the string diagram above the colored segment was added in a quick architecture design sync during a discussion centered around reporting requirements. The flexibility of the drawing gives us the power to make these changes live, but it’s the mathematical formalism that gives the whole team common ground to interpret exactly what those changes mean.
-
Unison Language and Platform Roadmap
Learn where Unison is headed
Check out what we’re excited about and working on at the moment 😎
The roadmap is of course not an exhaustive list of our efforts and is very much subject to change.
- Resolving architecture build errors on Apple silicon
Update your app’s architecture build settings to support building macOS, iOS, watchOS, and tvOS apps on Apple silicon.
- Pattern matching on error codes
tl;dr Foundation overloads the pattern matching operator
~=
to enable matching against error codes incatch
clauses. - Implicitly Opened Existentials
Fundamentally, opening an existential means looking into the existential box to find the dynamic type stored within the box, then giving a "name" to that dynamic type. That dynamic type name needs to be captured in a generic parameter somewhere, so it can be reasoned about statically, and the value with that type can be passed along to the generic function being called. The result of such a call might also refer to that dynamic type name, in which case it has to be erased back to an existential type. The After the call, any values described in terms of that dynamic type opened existential type has to be type-erased back to an existential so that the opened type name doesn't escape into the user-visible type system. This both matches the existing language feature (opening an existential value when accessing one of its members) and also prevents this feature from constituting a major extension to the type system itself.
This section describes the details of opening an existential and then type-erasing back to an existential. These details of this change should be invisible to the user, and manifest only as the ability to use existentials with generics in places where the code would currently be rejected. However, there are a lot of details, because moving from dynamically-typed existential boxes to statically-typed generic values must be carefully done to maintain type identity and the expected evaluation semantics.
- buildLimitedAvailability(_:)
Provides support for “if” statements with
#available()
clauses in multi-statement closures, producing conditional content for the “then” branch, i.e. the conditionally-available branch. - Reeder 5
Keep control of your news reading with Reeder, RSS reader and read later client in one app, now with support for iCloud syncing.
- How to implement dependent types in 80 lines of code
As an application of the developed system, I present a classical example of using dependent types: vectors parameterized by their length. Since vector lengths now dwell on type-level, we can guarantee statically that, for example, the
replicate
operation returns a vector of a given length,concat
returns a vector whose length is equal to the sum of lengths of two passed vectors, andzip
takes two vectors of the same length and returns a vector of that length. The code relies on some rudimentary facilities of Church numerals and pairs, which also serve as a warm-up. - Levity Polymorphism
I go back and forth on whether it makes sense for us to seriously write up the implementation of Swift generics. Is it "just engineering"?
The runtime generics implementation might be novel. SPJ published a paper saying it can't be done
The key thing they missed was our "reabstraction" concept. M:N relationship between types and concrete representations is pretty novel
- How to remove git commit history
- git checkout --orphan latest_branch
- git add -A
- git commit -am "Initial commit message"
- git branch -D main
- git branch -m main
- git push -f origin main
- git gc --aggressive --prune=all # remove the old files
- React Error Boundaries
In the past, JavaScript errors inside components used to corrupt React’s internal state and cause it to emit cryptic errors on next renders. These errors were always caused by an earlier error in the application code, but React did not provide a way to handle them gracefully in components, and could not recover from them.
- Introducing XCTModify
This PR introduces a more streamlined way to perform an in-place mutation of a case in an enum when in a testing context.
You should think of XCTModify as a companion to XCTUnwrap as it allows you to safely unwrap a case from an enum, and then further apply a mutation. This helper will be very useful for the navigation tools being built for TCA.
try XCTModify(&result, case: /Result.success) {
$0 += 1
}
- Xcode tip: sharing breakpoints across projects
Luckily, Xcode has a solution to this — User Breakpoints! After creating any breakpoint, you can right-click and select: “Move Breakpoint To” > “User” to move it from your project or workspace to user space. After this, you’ll see a shared list of User Breakpoints in every Xcode project you open.
- Shake Gesture in SwiftUI
SwiftUI doesn’t support natively shake gestures yet. But it’s easy to implement it in SwiftUI.
We need to create an extension for
UIDevice
for tracking shaking gestures when happens. Also, we need to create an extension forUIWindow
, and overridemotionEnded
method.
extension UIWindow {
override func motionEnded(_ motion: UIEvent.EventSubtype, with: UIEvent?) {
guard motion = .motionShake else { return }
NotificationCenter.default.post(name: UIDevice.deviceDidShake, object: nil)
}
}
- Base
Base is a secure, low-cost, developer-friendly Ethereum L2 built to bring the next billion users to web3.
- Reliably testing code that adopts Swift Concurrency?
class ViewModel: ObservableObject {
@Published var count = 0
enum Progress {
case didSubscribeToScreenshots, didRespondToScreenshot
}
// set to non-nil when testing
var progress: AsyncChannel<Progress>?
@MainActor
func task() async {
let screenshots = NotificationCenter.default.notifications(
named: UIApplication.userDidTakeScreenshotNotification
)
await progress?.send(.didSubscribeToScreenshots)
for await _ in screenshots {
self.count += 1
await progress?.send(.didRespondToScreenshot)
}
}
}
@MainActor
func testBasics() async throws {
let vm = ViewModel()
// Install a progress channel into the ViewModel we can monitor
let vmProgress = AsyncChannel<ViewModel.Progress>()
vm.progress = vmProgress
// We get `task.cancel(); await task.value` for free with async let
async let _ = vm.task()
XCTAssertEqual(vm.count, 0)
// Give the task an opportunity to start executing its work.
let firstProgress = await vmProgress.next()
XCTAssertEqual(firstProgress, .didSubscribeToScreenshots)
// Simulate a screen shot being taken.
NotificationCenter.default.post(
name: UIApplication.userDidTakeScreenshotNotification, object: nil
)
// Give the task an opportunity to update the view model.
let nextProgress = await vmProgress.next()
XCTAssertEqual(nextProgress, .didRespondToScreenshot)
XCTAssertEqual(vm.count, 1)
}
- the meta-algorithm for writing software is
- Decompose the problem into its constituent mental pieces
- Solve the problem there
- Mentally compile the solution into software
- Learn HTML
This HTML course for web developers provides a solid overview for developers, from novice to expert level HTML.
- Installing and managing Simulator runtimes
A Simulator runtime is an embedded OS package that Simulator loads when running your app on a simulated device in Xcode. For example, when you test your app on a simulated iPhone running iOS 16, Simulator loads the iOS 16 Simulator runtime on the simulated device.
To minimize the download size of Xcode, version 14 and later don’t include the Simulator runtimes for watchOS and tvOS. You need the current versions of the Simulator runtimes to build projects and to run the Simulator for those platforms. You can download and install these files when you first launch Xcode, or later from the Xcode run destination, from Xcode Preferences, or from the command line.
Manage the amount of storage that Xcode requires by choosing Xcode > Preferences > Platforms to view the currently installed Simulator runtimes, and removing any that you don’t need.
- Multipeer Connectivity
Support peer-to-peer connectivity and the discovery of nearby devices.
The Multipeer Connectivity framework supports the discovery of services provided by nearby devices and supports communicating with those services through message-based data, streaming data, and resources (such as files). In iOS, the framework uses infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks for the underlying transport. In macOS and tvOS, it uses infrastructure Wi-Fi, peer-to-peer Wi-Fi, and Ethernet.
- Struct and enum accessors take a large amount of stack space
We recently found an issue where the compiler was failing to reuse stack space between switch cases, and allocating the stack space necessary for all of the enum payloads and cases' local state even though only one actually executes at a time. You might be running into the same problem.
Until we fix that issue, one workaround we've found for this issue is to wrap up each case block in an immediately-invoked closure, like:
switch foo { case .bar: _ = { ... }() case .bas: _ = { ... }() }
If you see stack size issues even after adopting indirect cases, you might try that to see if it helps.
- ToolbarTitleMenu
The title menu of a toolbar.
- The Art of Sequential Animations in SwiftUI: Tips, Tricks, and Examples
Sequential Animations in SwiftUI offer a powerful and intuitive way to create dynamic and engaging user interfaces. By leveraging the power of SwiftUI’s animation system, developers can easily create complex and beautiful animations that add polish and delight to their apps.
With a few lines of code, animations can be sequenced and coordinated to create more intricate and expressive user experiences, making SwiftUI an excellent choice for building modern, interactive apps.
- Simulator: Save as GIF
After recording a video with the simulator, hold down the Control key while clicking the small preview. The simulator opens a menu. Select “Save as Animated GIF”.
- In Xcode 14.3 you can now see the output from your previews in the console!
In Xcode 14.3 you can now see the output from your previews in the console!
Just select the new previews button and you’ll see every print 🤯
Combine this with _printChanges() and you can debug views without running your app 🕵🏼
- Dynamic Library Usage Guidelines
The dynamic loader compatibility functions provide a portable and efficient way to load code at runtime. However, using the functions incorrectly can degrade app performance. This article shows how to correctly load and use dynamic libraries in your apps.
Dynamic libraries help to distribute an app’s functionality into distinct modules that can be loaded as they are needed. Dynamic libraries can be loaded either when the app launches or as it runs. Libraries that are loaded at launch time are called dependent libraries. Libraries that are loaded at runtime are called dynamically loaded libraries. You specify which dynamic libraries your app depends on by linking your app with them. However, it’s more efficient to use dynamic libraries as dynamically loaded libraries instead of dependent libraries. That is, you should open libraries when you’re about to use symbols they export and close them when you’re done. In some cases, the system unloads dynamically loaded libraries when it determines that they aren’t being used.
This article uses the word image to refer to an app file or a dynamic library. App binaries contain the app’s code and the code from the static libraries the app uses. The dynamic libraries the app loads at launch time or runtime are separate images.
- EditKit Pro
Elevate your iOS Development game with EditKit Pro — the ultimate Xcode Editor Extension packed with convenient utilities for a more efficient and productive workflow.
- The Swift Programming Language
Understand the high-level goals of the language.
- WebURL Key-Value Pairs
In order to make it easier to read/write key-value pairs from URL components, WebURL 0.5.0 will include a new KeyValuePairs type. The current formParams view will be deprecated and removed in the next minor release.
- The Art of Sequential Animations in SwiftUI: Tips, Tricks, and Examples
With a few lines of code, animations can be sequenced and coordinated to create more intricate and expressive user experiences, making SwiftUI an excellent choice for building modern, interactive apps.
- What Is Copy On Write(COW) In Swift?
Copy-On-Write (COW) is a memory management technique used in Swift programming language to optimize the performance of memory allocation and deallocation operations. In COW, whenever a new instance of a data structure is created, the original data structure is not modified, instead, a new copy of the data structure is created in memory and modifications are made to the new copy. Copy-on-write is a highly used strategy in Swift for optimising memory usage. The main idea of COW is that when multiple callers want to access the resources which are same, you can put them pointing to the same resource. The state of the resource will be maintained until a caller tries to modify its “copy” of the resource. The main advantage is that if a caller never makes any modifications, no true copy need ever be created. Don’t confuse copy on right with reference type.
- The Change of Mobile Teams Topology for an Organization
Optimize the structure of mobile teams to fit the need of the organization in scaling app development.
- iOS and iPadOS usage
As measured by devices that transacted on the App Store.
- Composable Styles in SwiftUI
A look at how to compose styles and how to make custom views support composable styles.
- pointfreeco/swift-clocks
⏰ A few clocks that make working with Swift concurrency more testable and more versatile.
- Creating an XCFramework
The key pieces to know when doing tackling this are embedded in the core of the article: Creating a multiplatform binary framework bundle:
- For a single library, use the
xcodebuild -create-xcframework
command with the-library
option. There’s also a-framework
option, but reserve that for when you need to expose multiple static, or dynamic, libraries as a binary deliverable. - Avoid using dynamic libraries in when you want to support iOS and iOS simulator, as only macOS supports the dynamic linking for these using a Framework structure. Instead, use static libraries.
- Use the
lipo
command to merge libraries when you’re building for x86 and arm architectures, but otherwise DO NOT combine the static libraries for the different platforms. You’ll want, instead, to have separate binaries for each platform you’re targeting. - These days, the iOS simulator libraries need to support BOTH x86 and arm64 architectures, so yep — that’s where you use
lipo
to merge those two into a single “fat” static library — at least if you’re targeting the iOS simulator on macOS. Same goes for supporting the macOS platform itself. - Get to know the codes called “triples” that represent the platforms you’re targeting. In the world of Rust development, three Apple platforms are “supported” without having to resort to nightly development: iOS, iOS simulator, and macOS. The “triples” are strings (yep — no type system here to double-check your work). Triple is ostensibly to support “CPU”, “Vendor”, and “platform” — but like any fairly dynamic type thing, it’s been extended a bit to support “platform variants”.
The triple codes you’ll likely want to care about, and their platforms:
- x86_64-apple-ios — the original iOS Simulator on an Intel Mac
- aarch64-apple-ios-sim — the iOS simulator on an M1/arm based Mac.
- aarch64-apple-ios — iOS and iPadOS (both are only arm architectures)
- aarch64-apple-darwin — M1/arm based Macs
- x86_64-apple-darwin — Intel based Macs
- For a single library, use the
- A Beginner’s Guide to Styling Components in SwiftUI
In conclusion, the SwiftUI ButtonStyle protocol is a versatile and straightforward tool for customizing the look and feel of your buttons in your iOS app.
Whether you’re a seasoned developer or just starting out, this protocol can help you create buttons that are both functional and visually appealing. So if you’re looking to add a personal touch to your buttons, be sure to check out SwiftUI’s ButtonStyle protocol!
- Genius by Diagram
It understands what you’re designing and makes suggestions that autocomplete your design using components from your design system.
- Developer Conferences Agenda
- Managing a merge queue
You can increase development velocity with a merge queue for pull requests in your repository.
A merge queue can increase the rate at which pull requests are merged into a busy target branch while ensuring that all required branch protection checks pass.
Once a pull request has passed all of the required branch protection checks, a user with write access to the repository can add that pull request to a merge queue.
A merge queue may use GitHub Actions. For more information, see "GitHub Actions."
The merge queue creates temporary branches with a special prefix to validate pull request changes. The changes in the pull request are then grouped into a
merge_group
with the latest version of thebase_branch
as well as changes ahead of it in the queue. GitHub will merge all these changes intobase_branch
once the checks required by the branch protections ofbase_branch
pass. - Adding a stretchable header to a SwiftUI ScrollView
The
ScrollViewHeader
presented in this post lets you add stretchable headers to your scroll views by just adding your content to this header component.I have added this view to my newly released ScrollKit library. You can find the source code here. If you decide to give it a try, I’d be very interested in hearing what you think.
- Styling Components in SwiftUI
SwiftUI has a great API for styling views independent of a view’s implementation. In this post, we’ll look at how we can style custom views in the same way.
- Changing orientation for a single screen in SwiftUI
Before you go, I want to stress that while this is the only workaround that we were able to find, it is by no means a robust and future-proof solution. We have found that navigation behaviour in SwiftUI tends to change in every iOS version and changing a single screen from portrait to landscape orientation works well on iOS 16 but not on iOS 15, where you'll probably want to set the orientation to allow
.allButUpsideDown
rather than constraining it to.landscape
only.For this reason, I would take what has been discussed in this article with a big pinch of salt and make sure you have sufficient UI/manual tests around the screen you're locking orientation for.
- If your iPhone won't turn on or is frozen
If your iPhone has a frozen screen, doesn't respond when you touch it, or becomes stuck when you turn it on, learn what to do.
On your iPhone 8 or later, including iPhone SE (2nd and 3rd generation)
- Press and quickly release the volume up button.
- Press and quickly release the volume down button.
- Press and hold the side button until you see the Apple logo.
- [Pitch] Type Wrappers
I've been working on the implementation for attached macros, and I had the chance to implement @Observable from the Future Directions section of the observation pitch. I was able to replicate the functionality in this type wrapper pitch through composition of the various attached macro capabilities.
The macro approach provides more flexibility, because the macro author can decide what code to generate inside the wrapped type. The macro-expanded code then becomes much more transparent to the programmer than a subscript call, which isn't very informative in terms of what that call accomplishes. The macro still has the ability to add backing storage variables, initializers, nested types derived from stored properties of the wrapped type, and more, and the transformation can be customized depending on what kind of type the macro is attached to (e.g. a
struct
versus anactor
).After taking the motivating use cases surfaced in this pitch thread and implementing them as macros, I'm confident that macros can fully subsume type wrappers while providing more flexibility to library authors.
- SwiftUI TextEditor Keyboard Avoidance
struct ContentView: View {
@State private var text: String = ""
init() {
UITextView.appearance().backgroundColor = .clear
}
@FocusState var inFocus: Int?
var body: some View {
ScrollViewReader { sp in
ScrollView {
TextEditor(text: $text).id(0)
.focused($inFocus, equals: 0)
.frame(height: 300)
.background(.yellow)
TextEditor(text: $text).id(1)
.focused($inFocus, equals: 1)
.frame(height: 300)
.background(.mint
TextEditor(text: $text).id(2)
.focused($inFocus, equals: 2)
.frame(height: 300)
.background(.teal)
if inFocus == 2 {
Color.clear.frame(height: 300)
}
}
.onChange(of: inFocus) { id in
withAnimation {
sp.scrollTo(id)
}
}
}
}
}
}
- A path of pain with URLCache eviction and subclassing
If you need to control the eviction strategy, or to implement your own storage, you'll have to do custom caching completely outside Foundation URL loading.
- How to cancel a background task in Swift
The async/await syntax, introduced in Swift 5.5, allows a readable way to write asynchronous code. Asynchronous programming can improve performance of an app, but it is important to cancel unneeded tasks to ensure unwanted background tasks do not interfere with the app. This article demonstrates how to cancel a task explicitly and shows how the child tasks are automatically cancelled.
- Keyboard Avoidance for SwiftUI Views
Whenever the iOS keyboard appears, it overlaps parts of your interface. The common approach to keyboard management is to move up the focused part of the view to avoid its overlapping. In this article, let’s learn how we can solve this problem by making our SwiftUI views keyboard-aware.
- The Swift Programming Language 5.7 : Quick Reference Guide
- Lenses, Transducers, and Algebraic Effects
- Understanding transducers
First, a bit of theory. A transducer is a function that describes the process of transformation, without knowing how exactly the thing it transforms is organized. It is not the same as generic functions, because transducers are generic in a bit different way.
- Styling Components in SwiftUI
SwiftUI has a great API for styling views independent of a view’s implementation. In this post, we’ll look at how we can style custom views in the same way.
- Per Martin-Löf: Transcriptions
This page collects transcriptions of lectures, mainly of a philosophical nature, given by Per Martin-Löf between the autumn of 1993 and September 2019. Most of them are published here for the first time. Each transcription contains a prefatory note outlining its origin.
- Ice Cubes: for Mastodon
Ice Cubes is a fast, reliable and beautiful Mastodon client.
- ClimateTechList.com
Joining a breakout company furthers your career growth.
Joining a climate tech company lets you build stuff that actually matters.
Now you can do both.
- 30,000 lines of SwiftUI in production later: We love it but you know there was going to be a “but”
In general, if you got yourself in a pickle — like I did several times — don’t do what I did every time: just as I naively set unnecessary/non-optimal publishers to begin with, I foolishly thought the opposite — removing any that seem unnecessary — is the way to go. Before you remove any, study the property’s trail. I had a few examples of a removal not immediately having any visible consequences, only for it become apparent after some time when the view didn’t respond to changes in a specific scenario. Finally, in case I forget again, remember an
@EnvironmentObject
will trigger a view update even if the view has no reference to any of its properties. - Container Pattern in SwiftUI
The main idea behind container pattern revolves around two different kind of views namely container and presenter/presentation views. The container view is responsible for fetching the data, sorting, filtering and other operations and then passing it down to presentation view for display.
In other words, container is a smart view and presenter is a dumb view. The only job of the presenter view is to display data on the screen. Data is always passed down from the container view to the presenter view.
- Is your SwiftUI ScrollView scrolling to the wrong location in iOS 15?
The workaround? Rejig your
ForEach
to return only “one view” that matches the frame you want to use withscrollTo(id:,anchor:)
— in my case I map my model data to an array of new enum types that describe what theForEach
should output for each iteration. - Using complex gestures in a SwiftUI ScrollView
Using complex gestures in a SwiftUI
ScrollView
is complicated, since they block scroll view gestures in a way that causes scrolling to stop working. I’ve looked into this, and found a way to use a button style to handle gestures in a way that doesn’t block the scrolling. - Pragmatic Testing and Avoiding Common Pitfalls
The main purpose of writing tests is to make sure that the software works as expected. Tests also gives you confidence that a change you make in one module is not going to break stuff in the same or other modules.
Not all applications requires writing tests. If you are building a basic application with a straight forward domain then you can test the complete app using manual testing. Having said that in most professional environments, you are working with a complicated domain with business rules. These business rules form the basis on which company operates and generates revenue.
In this article, I will discuss different techniques of writing tests and how a developer can write good tests to get the most return on their investment.
- PointFree LiveStream
- How to setup CloudKit subscription to get notified for changes
CloudKit subscription offers best way to keep data up-to-date for your user. I will show you the simplest setup to get started in this cloudkit subscriptions tutorial.
- Cracking the iOS-Developer Coding Challenge, SwiftUI Edition
In a recent post, I presented an approach for succeeding on take-home iOS-developer coding challenges. (For brevity, I henceforth refer to these particular coding challenges as “coding challenges”.) The model solution in that post used UIKit because, at the time I wrote the post, I had already completed coding challenges using that framework. But SwiftUI may be a good, or indeed the best, option.
- Using JavaScript in a Swift app
Calling JavaScript from Swift code is easily possible, although this isn’t friction-free. The interoperability is nowhere close to as good as between Swift and Objective-C. It’s also obvious that the JavaScriptCore API was designed for Objective-C and hasn’t been properly refined for Swift. That said, in the end, I’d rather have a more robust solution to a problem regardless of the programming language used to implement that solution, even if this means a little more friction.
- Poly: a category of remarkable abundance
- SwiftUI under the Hood: Variadic Views
Matching SwiftUI’s view APIs in their ergonomics is hard to get right. In this post we’ll learn how to write view APIs that feel truly native to the platform.
- Roc for Elm programmers
Roc is a direct descendant of the Elm programming language. The two languages are similar, but not the same!
This is a guide to help Elm programmers learn what's different between Elm and Roc.
- Variadic Views
To deal with these lists of views (e.g. during layout) we can use the underscored variadic view API. I learned about variadic views through the Moving Parts blog. I don’t know whether this API is going to change in the future, whether it’s App-Store-proof, and so on. It’s probably underscored for a good reason.
- Gaining access to Command-line from XCTest
We need to create an HTTP server that will be listening for requests. Then we can send a request from XCTest to the server and run whatever we want. The server can even return the output back to XCTest if required.
- Save money when using GitHub Actions for iOS CI/CD
For private repositories, each GitHub account receives a certain amount of free minutes and storage for use with GitHub-hosted runners, depending on the product used with the account. Any usage beyond the included amounts is controlled by spending limits.
MacOS-based runner images are expensive for GitHub and hence GitHub applies a minute multiplier.
- Disconnect your app from unit testing
It is similar for SwiftUI. But the new framework did away with AppDelegate, and has a simplified main func. You simply call
MyApp.main()
in main.swift to start an app. - Lifetime of State Properties in SwiftUI
Surprisingly Subtle
One of the challenging parts of SwiftUI is really understanding the way it manages view state (for example, through @State and @StateObject). In theory, it’s pretty simple: anytime you want associated view state you just create a property with @State and you’re done.
- SwiftUI Views are Lists
The View Protocol Has A Misleading Name
When you write SwiftUI, all your views conform to the View protocol. The name of this protocol is a bit misleading: I it could be called Views or ViewList, or something else that suggests plurals.
- Environment Values as an Alternative to Dependency Injection in SwiftUI
Using Environment Values to avoid unnecessary body re-evaluations and make our views more self-contained.
- The Nested Observables Problem in SwiftUI
Today we explore 3 solutions for this interesting problem in SwiftUI.
The first was binding the nested property to a View @State annotation, which would definitely trigger the View Redraw, but is not a good solution leaving the View entangled with the View data nested structure. The bright side of this approach is that this solution has zero effects on the Data layers, so if you don’t want to touch other layers’ code, this is one idea.
The second one was manually calling the
objectWillChange.send()
. This is also cumbersome because you need to remember to add the objectWillChange call every time you want to update the view. This is the receipt for bugs.And lastly, we checked what is for me the best answer to this problem. If you can, remove the nested observed object and make two simple ObservedObjects.
- Accessing a Swift property wrapper’s enclosing instance
However, if we take a look at the Swift Evolution proposal for the property wrappers feature, we can see that it also mentions a second, alternative way of handling a wrapper’s value...
- func typeName( type: Any.Type, qualified: Bool = true) -> String
Returns the demangled qualified name of a metatype.
- func typeByName( name: String) -> Any.Type?
Lookup a class given a name. Until the demangled encoding of type names is stabilized, this is limited to top-level class names (Foo.bar).
- How To Speed Up Swift By Ordering Conformances
You can generate an order file that has this result by parsing the linkmap file. All protocol conformances end in Mc so you just need the Swift symbol names matching this pattern that are in the
__TEXT/__const
section. You could write a detailed parser for the structure of a linkmap, but a simple grep should also do the trick:cat Binary-arm64-LinkMap.txt | grep -v '<<dead>>|non-lazy-pointer-to-local' | grep -o '_$.*Mc$' > order_file.txt
That’s it! You now have your order file. You can set the Xcode "Order File" build setting to the path of this file, or check out our docs with instructions on third party build systems. For something this easy to make, it is definitely worth doing to speed up the app for iOS 15 users or the first launch after an app update on iOS 16.
- Swift Algorithm Club
Here you'll find implementations of popular algorithms and data structures in everyone's favorite new language Swift, with detailed explanations of how they work.
If you're a computer science student who needs to learn this stuff for exams — or if you're a self-taught programmer who wants to brush up on the theory behind your craft — you've come to the right place!
The goal of this project is to explain how algorithms work. The focus is on clarity and readability of the code, not on making a reusable library that you can drop into your own projects. That said, most of the code should be ready for production use but you may need to tweak it to fit into your own codebase.
Code is compatible with Xcode 10 and Swift 4.2. We'll keep this updated with the latest version of Swift. If you're interested in a GitHub pages version of the repo, check out this.
- Data Laced with History: Causal Trees & Operational CRDTs
But even more remarkable is the discovery of Causal Trees and operation-based CRDTs. With this deconstruction of the CRDT formula, there’s finally a consistent way to understand, design, and implement arbitrary replicated data types. By breaking up conventional data structures into immutable micro-operations that are defined in absolute terms, giving them authorship and causality metadata, and carefully ordering them inside simple containers, you get the resilience and clarity of a convergent event log together with the efficiency of a low-level data structure. Conflict resolution can be precisely tailored to fit the needs of the data model. Operations can just as easily be sent around as-is or condensed into state snapshots. Version vectors can be used to perform garbage collection, view past revisions, or generate delta patches. Every last edit can be sourced to its author, placed in its historical and spatial context, and linked to from the outside. And all this is possible while simplifying the app’s architecture, not complicating it, since the paradigm is almost entirely functional!
- Apple Silicon
Get the resources you need to create software for Macs with Apple silicon.
Build apps, libraries, frameworks, plug-ins, and other executable code that run natively on Apple silicon. When you build executables on top of Apple frameworks and technologies, the only significant step you might need to take is to recompile your code for the arm64 architecture. If you rely on hardware-specific details or make assumptions about low-level features, modify your code as needed to support Apple silicon.
Getting the best performance on Apple silicon sometimes requires making adjustments to the way you use hardware resources. Minimize your dependence on the hardware by using higher-level technologies whenever possible. For example, use Grand Central Dispatch instead of creating and managing threads yourself. Test your changes on Apple silicon to verify that your code behaves optimally.
- Compiling for iOS on Apple M1
This article provides a quick overview of the compilation process and available architectures on Xcode with one goal in mind: Get a better understanding on what it means to compile for the M1.
- Death of a Craftsman
And all would be pretty much well if that were all there was to it. A simple, unproblemtic story. But then there is the third category: the ivory tower zealots! These are terrible! They have passion but they use it all wrong! They have principles but they are wrong! They could be into category theory instead of SOLID! Unrealistic! Unpragmatic! Proofs! Maths! Maybe they write comments or even specifications!
- Partial block result builder fails to pick correct overload and generates compiler error
I understand what you mean, this kind of workflow is not what is going to be supported by result builder transform implementation going forward. The result builder transform semantics are such that each element in the body is type-checked independently from others and the resulting value is then passed to a final
buildBlock
or a series ofbuildPartialBlock
calls and returned just like I outlined in my example, the old implementation failed to enforce the "solved independently" bit which caused all sorts of diagnostics and performance issues.In your example there are two overloads of
parser(of:)
method, both have argument that accepts a default value which means that the type-checker won't be able to disambiguate between them withoutbuildExpression
orbuildPartialBlock
providing more context (via generic requirements) just like if you wrote_ = Int.parser()
without using result builders. - Caching network data
Your quake client fetches a list of earthquakes from the network. Now, you’ll extend the client to fetch location details for each earthquake. Each earthquake requires one additional fetch to retrieve the location information. You’ll make multiple network connections concurrently while maintaining a cache of replies.
- Reverse Engineering SwiftUI’s NavigationPath Codability
It’s incredible to see what Swift 5.7’s existential types unlock. They allow us to create an interface that for all intents and purposes is dynamic, being an array of
Any
values, while simultaneously being able to pull static type information from it when needed. This allows for building tools that are both flexible and safe, such asNavigationStack
, which helps decouple domains in a navigation stack while simultaneously retaining type information to pass to destination views. - NavPath.swift
Reverse engineering SwiftUI's NavigationPath
- Transferable
A protocol that describes how a type interacts with transport APIs such as drag and drop or copy and paste.
- Bringing Photos picker to your SwiftUI app
Select media assets by using a Photos picker view that SwiftUI provides.
- Image Caching with URLCache
Store images, and other media files to memory or storage with URLCache — an alternative to NSCache.
- A roadmap for improving Swift performance predictability: ARC improvements and ownership control
Swift's high-level semantics try to relieve programmers from thinking about memory management in typical application code. In situations where predictable performance and runtime behavior are needed, though, the variability of ARC and Swift's optimizer have proven difficult for performance-oriented programmers to work with. The Swift Performance team at Apple are working on a series of language changes and features that will make the ARC model easier to understand, while also expanding the breadth of manual control available to the programmer. Many of these features are based on concepts John McCall had previously sketched out in the Ownership Manifesto ([Manifesto] Ownership), and indeed, the implementation of these features will also provide a technical foundation for move-only types and the other keystone ideas from that manifesto. We will be posting pitches for the features described in this document over the next few months.
We want these features to fit within the "progressive disclosure" ethos of Swift. These features should not be something you need to use if you're writing everyday Swift code without performance constraints, and similarly, if you're reading Swift code, you should be able to understand the non-ARC-centric meaning of code that uses these features by ignoring the features for the most part. Conversely, for programmers who are tuning the performance of their code, we want to provide a predictable model that is straightforward to understand.
- Accessing Cached Data
Control how URL requests make use of previously cached data.
- Google Nearby Connections API
Nearby Connections enables advertising, discovery, and connections between nearby devices in a fully-offline peer-to-peer manner. Connections between devices are high-bandwidth, low-latency, and fully encrypted to enable fast, secure data transfers.
A primary goal of this API is to provide a platform that is simple, reliable, and performant. Under the hood, the API uses a combination of Bluetooth, BLE, and Wifi hotspots, leveraging the strengths of each while circumventing their respective weaknesses. This effectively abstracts the vagaries of Bluetooth and Wifi across a range of Android OS versions and hardware, allowing developers to focus on the features that matter to their users.
As a convenience, users are not prompted to turn on Bluetooth or Wi-Fi — Nearby Connections enables these features as they are required, and restores the device to its prior state once the app is done using the API, ensuring a smooth user experience.
- Solving "Required kernel recording resources are in use by another document" in Instruments
So you have a Swift Package Manager project, without an xcodeproj, and you launch Instruments, and try to profile something (maybe Allocations), and you receive the message “Required kernel recording resources are in use by another document.” But of course you don’t have any other documents open in Instruments and you’re at a loss, so you’ve come here. Welcome.
- PhotoKit
Work with image and video assets managed by the Photos app, including those from iCloud Photos and Live Photos.
- Are we server yet? Yes! And it's freaking fast!
Swift has a mature and production ready framework in Vapor and Smoke, and newer ones like Hummingbird. These provide everything you’d expect from a web framework, from routing and middleware, to templating, and JSON/form handling. There are packages for everything, and more!
- AsyncImage
A view that asynchronously loads and displays an image.
- withCheckedThrowingContinuation(function:_:)
Suspends the current task, then calls the given closure with a checked throwing continuation for the current task.
- CRAFTING INTERPRETERS
Crafting Interpreters contains everything you need to implement a full-featured, efficient scripting language. You’ll learn both high-level concepts around parsing and semantics and gritty details like bytecode representation and garbage collection. Your brain will light up with new ideas, and your hands will get dirty and calloused. It’s a blast.
- Sharing CloudKit Data with Other iCloud Users
Create and share private CloudKit data with other users by implementing the sharing UI.
- CloudKit Shared Records
Share one or more records with other iCloud users.
- What Advanced Data Protection for iCloud means for Tact and other apps that use CloudKit
Advanced Data Protection (ADP) for iCloud is the most intriguing of the three, and the rest of this post will discuss how it can improve the security of your data in Tact and other CloudKit-based apps.
TL;DR
for Tact: your Tact private chats will be end-to-end encrypted if all chat members have enabled Advanced Data Protection on their accounts.TL;DR
for any CloudKit app: your records in iCloud will be end-to-end encrypted if certain conditions are met. You have no way to verify some of the conditions on your end. - Designing and Creating a CloudKit Database
Create a schema to store your app’s objects as records in iCloud using CloudKit.
After you enable CloudKit in your app, you create a schema for your container that describes how to store your objects. A schema defines record types and the possible relationships between them. A record type is a template for the allowed keys and values of a record. This relationship is analogous to how a class (record type) defines the properties an instance (record) can have.
- CKRecord.Reference
A relationship between two records in a record zone.
A
CKReference
object creates a many-to-one relationship between records in your database. Each reference object stores information about the one record that is the target of the reference. You then save the reference object in the fields of one or more records to create a link from those records to the target. Both records must be in the same zone of the same database. - task(priority:_:)
Adds an asynchronous task to perform before this view appears.
- task(id:priority:_:)
Adds a task to perform before this view appears or when a specified value changes.
- Using cktool
cktool
is stateless and passes all operations to the CloudKit Management API in single operations. - Clarification needed on UnsafeContinuation documentation
They're both right. The task stops executing any async code at all before the continuation is formed, and any state will be moved off of the callstack into the task object at that point. The closure is then immediately executed in the same execution context (in other words, the current thread) with the closure as a parameter. Once the closure returns, control goes back to the executor.
- How to update HomePod after you have enabled Advanced Data Protection for iCloud
Learn what to do if you can’t set up or update your HomePod after Advanced Data Protection is enabled.
- CurrentValueSubject
A subject that wraps a single value and publishes a new element whenever the value changes.
Unlike PassthroughSubject, CurrentValueSubject maintains a buffer of the most recently published element.
- Freestanding Macros
SE-0382 "Expression macros" introduces macros into Swift. The approach involves an explicit syntax for uses of macros (prefixed by
#
), type checking for macro arguments prior to macro expansion, and macro expansion implemented via separate programs that operate on the syntax tree of the arguments.This proposal generalizes the
#
-prefixed macro expansion syntax introduced for expression macros to also allow macros to generate declarations and statements, enabling a number of other use cases, including:- Subsuming the
#warning
and#error
directives introduced in SE-0196 into macros. - Logging entry/exit of a function.
- Subsuming the
- Attached Macros
Attached macros provide a way to extend Swift by creating and extending declarations based on arbitrary syntactic transformations on their arguments. They make it possible to extend Swift in ways that were only previously possible by introducing new language features, helping developers build more expressive libraries and eliminate extraneous boilerplate.
- GitHub Blocks — Reimagine repositories
Extend your codebase with custom, interactive blocks.
Build rich documentation, enhance your workflows, and bring your repository to life.
- The latest GitHub previews ✨
Be the first to try out GitHub’s new features
- Truncating git history
git checkout --orphan temp e41d7f633c45c46bd42e97cecf93204191d9e4c9
git commit -m "Truncate history"
git rebase --onto temp e41d7f633c45c46bd42e97cecf93204191d9e4c9 master
- ImageRenderer
An object that creates images from SwiftUI views.
- How task locals work
Task locals are what power this library under the hood, and so it can be important to first understand how task locals work and how task local inheritance works.
Task locals are values that are implicitly associated with a task. They make it possible to push values deep into every part of an application without having to explicitly pass the values around. This makes task locals sound like a “global” variable, which you may have heard is bad, but task locals have 3 features that make them safe to use and easy to reason about:
- Task locals are safe to use from concurrent contexts. This means multiple tasks can access the same task local without fear of a race condition.
- Task locals can be mutated only in specific, well-defined scopes. It is not allowed to forever mutate a task local in a way that all parts of the application observe the change.
- Task locals are inherited by new tasks that are spun up from existing tasks.
- ViewToPDF
import SwiftUI
extension View {
@MainActor
func pdf(size: ProposedViewSize) -> Data {
let renderer = ImageRenderer(content: self)
renderer.proposedSize = size
var pdfData = NSMutableData()
renderer.render { size, render in
var mediaBox = CGRect(origin: .zero, size: size)
let consumer = CGDataConsumer(data: pdfData)!
let pdfContext = CGContext(consumer: consumer, mediaBox: &mediaBox, nil)!
pdfContext.beginPage(mediaBox: &mediaBox)
render(pdfContext)
pdfContext.endPage()
pdfContext.closePDF()
}
return pdfData as Data
}
}
- HTMLKit
Create and render HTML templates with HTMLKit.
- Writing Haskell with Chat GPT
So overall, Chat GPT does quite well with these basic challenges! It would be interesting to take this further still and see if we could make our server program more and more complex, like adding custom functionality for different routes. But Chat GPT definitely seems useful enough to help with basic tasks, even in a less well-known language like Haskell!
- TaskLocal
Property wrapper that defines a task-local value key.
A task-local value is a value that can be bound and read in the context of a
Task
. It is implicitly carried with the task, and is accessible by any child tasks the task creates (such as TaskGroup orasync let
created tasks). - ActorIsolated
A generic wrapper for isolating a mutable value to an actor.
- LockIsolated
A generic wrapper for isolating a mutable value with a lock.
- CKUserIdentity
A user identity provides identifiable data about an iCloud user, including their name, user record ID, and an email address or phone number. CloudKit retrieves this information from the user’s iCloud account. A user must give their consent to be discoverable before CloudKit can provide this data to your app. For more information, see requestApplicationPermission(_:completionHandler:).
- Neovim's Terminal Emulator
In Neovim, we can launch a terminal emulator by running the
:terminal
command. - BindableState
A property wrapper type that can designate properties of app state that can be directly bindable in SwiftUI views.
- BindableAction
An action type that exposes a
binding
case that holds a BindingAction. - BindingReducer
A
reducer
that updates bindable state when it receives binding actions. - TCA Working with SwiftUI bindings
Learn how to connect features written in the Composable Architecture to SwiftUI bindings.
- TCA Store
A store represents the runtime that powers the application. It is the object that you will pass around to views that need to interact with the application.
- omaralbeik/Stores
A typed key-value storage solution to store Codable types in various persistence layers like User Defaults, File System, Core Data, Keychain, and more with a few lines of code!
- 💡 The big idea
🧠
Each Unison definition is identified by a hash of its syntax tree.
Put another way, Unison code is content-addressed.
- Unison — Mermaid
Draw charts renderable using mermaid-js. Only sequence diagrams supported at the moment.
- Unison — Html
This is a small Html combinator library for building up an Html document. The API is 's heavily inspired by the Elm Html library.
- Making Haskell lenses less pointless
type Value f s t r = (s -> f t) -> f r
- Mac OS X and PDF
OS X is the first operating system on the market that actually uses PDF technology within the operating system itself. Apple calls this technology ‘Quartz’. Quartz is a layer of software that runs on top of Darwin, the core (or kernel) of the Mac OS X operating system. It is responsible for the rendering of all 2D objects. Alongside Quartz, OpenGL takes care of handling 3D data (used in games like Quake or Unreal as well as professional 3D applications like Maya) and QuickTime handles multimedia stuff (movies, sound,…).
- Compiled and Interpreted Languages: Two Ways of Saying Tomato
First that language specifications and implementations are very different things. Second, via the series of evolving BF implementations, that any given language can be implemented as an interpreter or a compiler.
- Understanding SwiftUI view lifecycles
Here are a few lessons to take away from this:
- Different container views may have different performance and memory usage behaviors, depending on how long they keep child views alive.
onAppear
isn’t necessarily called when the state is created. It can happen later (but never earlier).onAppear
can be called multiple times in some container views. If you need a side effect to happen exactly once in a view’s lifetime, consider writing yourself aonFirstAppear
helper, as shown by Ian Keen and Jordan Morgan in Running Code Only Once in SwiftUI (2022-11-01).
- Low-level Swift optimization tips
This article documents several techniques I have found effective at improving the run time performance of Swift applications without resorting to “writing C in .swift files”. (That is, without resorting to C-like idioms and design patterns.) It also highlights a few pitfalls that often afflict Swift programmers trying to optimize Swift code.
- Swift async/await in AWS lambdas
The changes for this unreleased 1.0 version include, among others, the adoption of
async/await
. In this article we'll rewrite an existing lambda to use the latestmain
revision of the swift-aws-lambda-runtime package and take an early look at what the new APIs look like and how they enable us to useasync/await
in AWS lambdas. - Text modifiers in SwiftUI
Apart from regular view modifiers in SwiftUI, there are also text modifiers. They apply specific styles to a
Text
view and return anotherText
rather thansome View
. We can see the list of available text modifiers in the Text view documentation under the "Styling the view’s text" and other sections. These are the ones that haveText
as their return type, for examplefunc foregroundColor(Color?) -> Text
. - Text
A view that displays one or more lines of read-only text.
- Swift Protocol Witness Matching Manifesto
- A protocol requirement (or just requirement) is a declaration inside a protocol that all conforming types must satisfy.
- A protocol witness (or just witness) is a value or a type that satisfies a protocol requirement.
- Unison Cloud Trailblazers Program
We are looking for people to help us try out unison.cloud before wider public release, and also to give us early feedback on brand new Unison Cloud functionality we're developing. If you're interested in participating in this program, please fill out this short questionaire and we'll get back to everyone within 7 days about next steps. We have somewhat limited space for now, so don't hesitate if you are interested!
- Unison HTTP Server
A Http server for the Unison Programming Language.
- Unison HTTP Client
This is an HTTP client library. It can be used to make HTTP requests and inspect their responses.
- Unison Optics
An attempt at an optics library for Unison — now with support for indexed and coindexed(!) optics!
- Unison Codec
This is a library for writing compositional binary codecs that can serialize and/or deserialize Unison values to and from binary formats. Functions are provided for writing and reading values to and fromBytes,network sockets, and files.
- Unison Language Server
Supported features:
- Autocompletion
- Inline type and parser error messages
- Show type on hover
- Memory Safe Languages in Android 13
To date, there have been zero memory safety vulnerabilities discovered in Android’s Rust code.
- allowsHitTesting(_:)
Configures whether this view participates in hit test operations.
- UIApplicationDelegateAdaptor
A property wrapper type that you use to create a UIKit app delegate.
- PreviewProvider
A type that produces view previews in Xcode.
- Previews in Xcode
Generate dynamic, interactive previews of your custom views.
- Improving the speed of incremental builds
Tell the Xcode build system about your project’s target-related dependencies, and reduce the compiler workload during each build cycle.
- Swift UI camera app without using UIView or UI*
In this article, I'm writing down my experience and codes that worked to get an app working in Swift UI that uses a user camera and shows a live feed on the screen. This app works in both macOS (Apple Silicon tested) and iOS.
- Android Basics with Compose
Welcome to Android Basics with Compose! In this course, you'll learn the basics of building Android apps with Jetpack Compose, the new UI toolkit for building Android apps. Along the way, you'll develop a collection of apps to start your journey as an Android developer.
- How to find which data change is causing a SwiftUI view to update
Peter Steinberger has a helpful tip for discovering when the
body property of a view is being reinvoked: assign a random background color to one of its views. This will be re-evaluated along with the rest of the
body`, so if body is being called a lot then your views will flicker as they change background. - Previewing Stateful SwiftUI Views — Interactive Previews for your SwiftUI views
When building UIs in SwiftUI, we tend to build two kinds of UI components: screens and (reusable) views. Usually, we start by prototyping a screen, which will inevitably result in a Massive ContentView that we then start refactoring into smaller, reusable components.
- Auto-Completion Feature Improvements in Xcode 14
Apple describes Xcode version 14 as "everything you need" to build software for their platforms. The company implemented a number of improvements, such as several updated auto-completion functions, to increase Xcode’s performance. Read on to find out which ones I have found particularly important and see how they work in practice.
- func runtimeWarn(_ message: @autoclosure () -> String, file: StaticString? = nil, line: UInt? = nil)
Xcode runtime warnings offer a much better experience than traditional assertions and breakpoints, but Apple provides no means of creating custom runtime warnings ourselves. To work around this, we hook into SwiftUI's runtime issue delivery mechanism, instead.
- Reliably testing code that adopts Swift Concurrency?
The calls to
Task.yield
feel wrong to me, but I don’t know of an alternative.The real problem with this code, though, is that the test occasionally fails! You can use Xcode’s “run repeatedly” feature 1,000 times and will almost always get a failure or two. From what I can gather, this is because there’s no guarantee that
Task.yield
will suspend long enough for the task to do its work.I can sprinkle in more
Task.yield
s and the test fails less often. - CloudKit.Notification
A
CloudKit.Notification
object represents a push notification that was sent to your app. Notifications are triggered by subscriptions that you save to the database. To subscribe to record changes and handle push notifications, see thesaveSubscription
method inCloudKit.Database
. - CloudKit Remote Records
Use subscriptions and change tokens to efficiently manage modifications to remote records.
- CRAttributes
Enables collaboration on text field (and other fields) across multiple iOS devices.
It's based on operation based CRDT with replication leveraging native CoreData CloudKit sync. A nearly vanilla implementation of CRDT RGA (operation per character).
- Designing for Key-Value Data in iCloud
To store discrete values in iCloud for app preferences, app configuration, or app state, use iCloud key-value storage. Key-value storage is similar to the local user defaults database; but values that you place in key-value storage are available to every instance of your app on all of a user’s various devices.
- NSUbiquitousKeyValueStore
An iCloud-based container of key-value pairs you use to share data among instances of your app running on a user's connected devices.
Use the iCloud key-value store to make preference, configuration, and app-state data available to every instance of your app on every device connected to a user’s iCloud account. You can store scalar values such as BOOL, as well as values containing any of the property list object types:
NSNumber
,NSString
,NSDate
,NSData
,NSArray
, andNSDictionary
. - All you need to know about CloudKit Art
Using
CloudKit
is an interesting solution for local iOS applications requiring synchronization among different devices. It allows simple storage of binary data such as photos or films as well as creating a more complicated database. However, if you want to store and synchronize a small amount of data among one user’s devices (e.g. a common configuration), it’s worth thinking about usingNSUbiquitousKeyValueStore
which also employs iCloud and doesn’t require configuring the CloudKit container. - Good Spirits: Syncing Data Statelessly
I intended for all this to lead to easy, stateless CloudKit sync. Instead of enforcing tight coupling between the persistence and cloud layers, I would have a “sync whenever” system that was guaranteed to succeed whenever it happened to run. Both the local SQLite database and CloudKit would keep around the same data and log tables. On sync, the local store would request the version vector from the CloudKit log table. Based on this timestamp, the local store would know which local check-ins needed to be uploaded, and could additionally request any check-ins from the server that were needed to complete the local database. Merge between check-ins was eventually consistent and conflict-free, and nothing was ever deleted, so you’d never need to do anything more complicated than send sets of check-ins and event log entries around. Sync would become completely stateless!
- Developing a Distributed Data App with SwiftUI and CRDTs
That’s all folks! In this series, we’ve seen how you can design and create your own replicating data types, and combine them to into full distributed data apps. These types have a data cost, but the payoff is that they make syncing more powerful and easier to implement. They also free your app from lock in — you can sync via any cloud service, and even peer-to-peer.
- CKAsset
An external file that belongs to a record.
Use assets to incorporate external files into your app’s records, such as photos, videos, and binary files. Alternatively, use assets when a field’s value is more than a few kilobytes in size. To associate an instance of
CKAsset
with a record, assign it to one of its fields. - Sharing data between your App Clip and your full app
Use CloudKit, Sign in with Apple, shared user defaults or containers, and the keychain to offer a smooth transition from your App Clip to your app.
- CloudKit JS
Provide access from your web app to your CloudKit app’s containers and databases.
- Module vs Product vs Target
- module: A group of interrelated sources intended to always be built together. (cf. whole module optimization). This is what is referenced when you
import MyModule
, and when you use its name for disambiguating a symbol:MyModule.Data
vsFoundation.Data
.- In general English, a module is “one of a set of standardized parts or independent units that can be used to construct a more complex structure”
- target: A unit of the build result; a particular thing you might aim to build on its own. A Swift target is pretty much equal to a Swift module, so they are often used interchangeably. However module tends to refer more to the grouping whereas target refers more to the result. Another difference is that a target does not necessarily have to contain source; it could be something else such as a resource bundle and such a target is not a module. Targets are referenced by the package manifest’s
.target(...)
andtestTarget(...)
, and by Xcode under “File → New → Target...” and so on.- In general English, a target is “a mark or point at which one fires or aims” or “an objective or result towards which efforts are directed”
- product: A unit of functionality you want to vend to clients. Often a product is also a single target, but the reverse is not true. Many targets are not intended for others to use (such as test targets), and those are never described as products. Products are defined in the package manifest’s
products
argument and referenced in client target’s dependency list with.product(...)
(unless the reference is reduced to a string literal).- In general English, a product is “an article or substance that is manufactured or refined for sale”
- module: A group of interrelated sources intended to always be built together. (cf. whole module optimization). This is what is referenced when you
- String to UInt32
"ptru”.utf8.reduce(0) { $0 << 8 | $1 }
- Faster Builds with Code Signing Hacks
Code signing is one of the few operations that takes just as long to do for an incremental build as for a clean build. It also takes more time the larger an app grows in size. As a result, it can become a bottleneck for incremental builds. Here are some tricks to reduce that time. They’re all technically undocumented and may break in the future, but they’re also used by large companies with no apparent downsides.
Note: these tricks are for debug builds only.
Note: see how much time code signing takes during builds, i.e. how much time you can actually save, and decide if that amount matters to you.
- vs — Autocomplete vs Graph
Have you ever noticed how Google auto-completes your queries?
What if we repeat the same query for every suggestion?
Now let's repeat this process one more time for every found suggestion. But instead of drawing a picture, let's draw a line between each suggestion
And this is exactly what this website is doing for You.
I found this technique useful to find alternatives, or to perform a market research. Obviously, for this technique to work, Google needs to know enough about your query.
- Faster Apple Builds with the lld Linker
TL;DR:
lld
is a great choice for faster linking of debug binaries on Apple platforms. Steps on how to integrate are in the section below.Linking is one of the main bottlenecks for incremental builds. Thousands upon thousands of developer-hours are spent each year waiting on debug builds to link, and so linker optimization is a major topic. Linkers are complicated beasts that have to do intricate transformations on huge amounts of data at lightning speed, so it requires a lot of work. This blog post will discuss the past, present, and future of linker optimization for Apple platforms. It also includes a practical section on how to integrate lld at present. If you aren’t familiar with linking, read about it here and look for the linking step at the end of your build logs.
- Measuring your iOS app’s true startup time in production (2018)
Before an app even runs
main
and+applicationDidFinishLaunching
, a considerable amount of work is done, including setting up dylibs for use, running+load
methods, and more. This can take 500ms or more. Blog posts like this one show you how to measure it with the debugger, usingDYLD_PRINT_STATISTICS
, but it’s hard to find any help for measurement in the wild. Note the special handling for iOS 15’s pre-warming feature. - Getting started with CloudKit
CloudKit is an easy way to store data in the cloud, sync between multiple devices, and share it between the app’s users. This week we will learn how to start using CloudKit in the app to save and fetch data from the cloud and sync between multiple user devices.
- Zone sharing in CloudKit
CloudKit provides you ready to use data sharing API that allows you to implement collaborative features of your app without much effort. There are two ways to share data via CloudKit: record sharing and zone sharing. In this post, we will talk about zone sharing.
- Small Design Up-Front Removes Agile — part 3
One of the footnotes in Agile is "small design up-front". Well what happens when that is done so well it removes the need for what Agile provides? During this meetup, we explored aspects of the software development life cycle that are affected by proper design. UML is an example of a 1:1 mapping of code to design documents. Instead, we can get on another level of understanding at an order of magnitude faster pace when we design information flow alone.
- Find Problematic Constraint
If you see a problematic constraint, copy its address from the console and use it to filter in the view debugger. The view debugger will show you the exact constraint in the user interface.
- Efficiently Managing Multiple Async Tasks in SwiftUI
We will use the
cancellation token
concept to solve an asynchronous problem in this week’s article today. - A Comprehensive Guide to URLs in Swift and SwiftUI
URLs can represent all kinds of resources.
How you handle a URL in your app depends on (a) the resource and (b) your app’s objectives and architectural considerations.
- Drawing Paths and Shapes
Users receive a badge whenever they visit a landmark in their list. Of course, for a user to receive a badge, you’ll need to create one. This tutorial takes you through the process of creating a badge by combining paths and shapes, which you then overlay with another shape that represents the location.
If you want to create multiple badges for different kinds of landmarks, try experimenting with the overlaid symbol, varying the amount of repetition, or changing the various angles and scales.
Follow the steps to build this project, or download the finished project to explore on your own.
- UI Testing using Page Object pattern in Swift
UI tests are expensive and fragile but vital and usable. That’s why you should take care of them as much as you take care of your main codebase. The Page Object pattern is a great way to simplify your UI tests and reuse the logic across the many UI tests.
- Link fast: Improve build and launch times (WWDC22 Notes)
Description: Discover how to improve your app's build and runtime linking performance. We'll take you behind the scenes to learn more about linking, your options, and the latest updates that improve the link performance of your app.
- dyld4 design
The goal of dyld4 is to improve on dyld3 by keeping the same mach-o parsers, but do better in the non-customer case by supporting just-in-time loading that does not require a pre-built closures.
- Stores
A typed key-value storage solution to store Codable types in various persistence layers like User Defaults, File System, Core Data, Keychain, and more with a few lines of code!
- Trie in Swift, the Autocorrect Structure
The Trie has a faster lookup than an imperfect hash map, doesn’t has key collision and the main use is to represent string dictionaries.
- MDM restrictions for Mac computers
You can set restrictions, including modifying a device and its features, for Mac computers enrolled in a mobile device management (MDM) solution.
- Storing Codable structs on the disk
Today we discussed a simple way of storing Codable structs which we can fetch via REST API. Sometimes we don’t need complicated features of CoreData for simple JSON caching and it is enough to implement disk storage.
- A Brand-New iOS Conference in New York City
New York, 04/18 & 04/19, 2023
- Toggle Changes/Repos
Toggle between changes and repositories in the Source Control navigator with the shortcut Command 2.
- Reveal In Changes Navigator
While you are in a file with local changes, use the shortcut Command Shift M to navigate to that file in the changes navigator.
- Swift Evolution Visions
Vision documents usually start by being solicited by the evolution workgroup with authority for that area. For areas within the Swift language and standard library, that is the Language Workgroup. While a vision is being developed, it is called a prospective vision, and it should be clearly identified as such. In this state, the vision carries no implicit endorsement.
Eventually, the appropriate evolution workgroup may decide to officially approve a vision. This is an endorsement of the entire document, but the strength of that endorsement varies from section to section:
- It is a strong endorsement of the vision's description of the current state of this part of the project. The evolution workgroup agrees with what the vision has to say about the problems the project has in this area.
- It is a strong endorsement of the vision's stated goals for this part of the language. The evolution workgroup agrees that these are the right goals for evolution in this area to strive for, and it agrees that the vision prioritizes different goals appropriately.
- It is a somewhat weaker endorsement of the overall approach laid out by the vision. The evolution workgroup agrees that this seems like the right basic approach to take; if it can successfully carried out, it should achieve the goals the vision lays out. However, the evolution workgroup is not committed to the details of the approach, and it may change substantially as the vision is distilled into concrete proposals and reviewed.
- It is only a very weak endorsement of the concrete ideas for proposals in the vision document. The evolution workgroup thinks these sound like the right ideas in the abstract but is not committed to any of them. The proposals will all need to go through normal evolution review, and they may be rejected or substantially changed from how they appear in the vision.
Once the vision is approved, it acts as a foundation for subsequent pitches and proposals in its area. Pitches and proposals that implement or build on part of a vision should generally link back to the vision document.
Vision documents are artifacts of the design process; they are not substitutes for language or release documentation. It is not expected that authors will continually update the vision document as the proposals emerging from it change. Revision may be appropriate if the vision document is actively causing confusion, for example because of a major shift in terminology since the document's development.
- Why does Apple recommend to use structs by default?
The consequence of this recommendation is that, from what I've seen in many projects, people tend to declare gigantic structs (esp. their JSON objects) and pass them around in functions or assign to variables without thinking that it can be a waste of memory and CPU cycles. In some edge cases the overhead can be significant and can be felt by the users.
- Building custom layout in SwiftUI. LayoutValueKey.
SwiftUI provides us with the LayoutValueKey protocol allowing us to register a custom layout parameter. We can use this type to attach any value we need to a view inside the layout and extract this value later in the layout cycle.
- BuildSettingCondition
A condition that limits the application of a build setting.
By default, build settings are applicable for all platforms and build configurations. Use the .when modifier to define a build setting for a specific condition. Invalid usage of .when emits an error during manifest parsing. For example, it’s invalid to specify a .when condition with both parameters as nil.
- Categories for AI
This lecture series consists of 2 parts , these being: the introductory lectures and the seminars. During the first part we'll have 1-2 introductory lectures per week, where we will teach the basics of category theory with a focus on applications to Machine Learning.
The seminars will be deep dives into specific topics of Category Theory, some already showing applications to Machine Learning and some which have not beeen applied yet.
- Xcode — Writing Testable Code
The Xcode integrated support for testing makes it possible for you to write tests to support your development efforts in a variety of ways. You can use tests to detect potential regressions in your code, to spot the expected successes and failures, and to validate the behavior of your app. Testing improves the stability of your code by ensuring that objects behave in the expected ways.
Of course, the level of stability you achieve through testing depends on the quality of the tests you write. Likewise, the ease of writing good tests depends on your approach to writing code. Writing code that is designed for testing helps ensure that you write good tests. Read the following guidelines to ensure that your code is testable and to ease the process of writing good tests.
- Define API requirements. It is important to define requirements and outcomes for each method or function that you add to your project. For requirements, include input and output ranges, exceptions thrown and the conditions under which they are raised, and the type of values returned (especially if the values are instances of classes). Specifying requirements and making sure that requirements are met in your code help you write robust, secure code. See the Unit Testing Apps and Frameworks sample-code project for an example of using exceptions to identify and report incorrect library usage by client code.
- Write test cases as you write code. As you design and write each method or function, write one or more test cases to ensure that the API’s requirements are met. Remember that it’s harder to write tests for existing code than for code you are writing.
- Check boundary conditions. If a parameter for a method must have values in a specific range, your tests should pass values that include the lowest and highest values of the range. For example, if a procedure has an integer parameter that can have values between
0
and100
, inclusive, the test code for that method should pass the values0
,50
, and100
for the parameter. - Use negative tests. Negative tests ensure that your code responds to error conditions appropriately. Verify that your code behaves correctly when it receives invalid or unexpected input values. Also verify that it returns error codes or raises exceptions when it should. For example, if an integer parameter must have values in the range
0
to100
, inclusive, create test cases that pass the values-1
and101
to ensure that the procedure raises an exception or returns an error code. - Write comprehensive test cases. Comprehensive tests combine different code modules to implement some of the more complex behavior of your API. Although simple, isolated tests provide value, stacked tests exercise complex behaviors and tend to catch many more problems. These kinds of tests mimic the behavior of your code under more realistic conditions. For example, in addition to adding objects to an array, you could create the array, add several objects to it, remove a few of them using different methods, and then ensure that the set and number of remaining objects are correct.
- Cover your bug fixes with test cases. Whenever you fix a bug, write one or more tests cases that verify the fix.
- XCTIssue
An object that represents a test failure, and includes source code call stacks for test reporting and investigation.
- Adding SQLCipher to Xcode Projects
SQLite is already a popular API for persistent data storage in iOS apps so the upside for development is obvious. As a programmer you work with a stable, well-documented API that happens to have many good wrappers available in Objective-C, such as FMDB and Encrypted Core Data. All security concerns are cleanly decoupled from application code and managed by the underlying framework.
The framework code of the SQLCipher project is open source, so users can be confident that an application isn't using insecure or proprietary security code. In addition, SQLCipher can also be compiled on Android, Linux, macOS and Windows for those developing cross-platform applications.
There are two different options for integrating SQLCipher into an Xcode project. The first involves building the SQLCipher source amalgamation into the application. The second involves using CocoaPods. These tutorials assume familiarity with basic iOS or macOS app development and a working install of Xcode.
- Internet Archive Scholar
Search Millions of Research Papers
This fulltext search index includes over 25 million research articles and other scholarly documents preserved in the Internet Archive. The collection spans from digitized copies of eighteenth century journals through the latest Open Access conference proceedings and pre-prints crawled from the World Wide Web.
- The Future of Foundation
Today, we are announcing a new open source Foundation project, written in Swift, for Swift.
This achieves a number of technical goals:
- No more wrapped C code. With a native Swift implementation of Foundation, the framework no longer pays conversion costs between C and Swift, resulting in faster performance. A Swift implementation, developed as a package, also makes it easier for Swift developers to inspect, understand, and contribute code.
- Provide the option of smaller, more granular packages. Rewriting Foundation provides an opportunity to match its architecture to evolving use cases. Developers want to keep their binary sizes small, and a new FoundationEssentials package will provide the most important types in Foundation with no system dependencies to help accomplish this. A separate FoundationInternationalization package will be available when you need to work with localized content such as formatted dates and time. Other packages will continue to provide XML support and networking. A new FoundationObjCCompatibility package will contain legacy APIs which are useful for certain applications.
- Unify Foundation implementations. Multiple implementations of any API risks divergent behavior and ultimately bugs when moving code across platforms. This new Foundation package will serve as the core of a single, canonical implementation of Foundation, regardless of platform.
And this also achieves an important community goal:
- Open contribution process. Open source projects are at their best when the community of users can participate and become a community of developers. A new, open contribution process will be available to enable all developers to contribute new API to Foundation.
- Coduo lets you share and collaborate in Xcode
Pair program and Chat in real-time. Simple, fast and effective.
- Advanced Data Protection for iCloud
Advanced Data Protection for iCloud is an optional setting that offers Apple’s highest level of cloud data security. When a user turns on Advanced Data Protection, their trusted devices retain sole access to the encryption keys for the majority of their iCloud data, thereby protecting it with end-to-end encryption. For users who turn on Advanced Data Protection, the total number of data categories protected using end-to-end encryption rises from 14 to 23 and includes iCloud Backup, Photos, Notes and more.
Advanced Data Protection for iCloud will be available to U.S. users by the end of 2022 and will start rolling out to the rest of the world in early 2023.
Conceptually, Advanced Data Protection is simple: All CloudKit Service keys that were generated on device and later uploaded to the available-after-authentication iCloud Hardware Security Modules (HSMs) in Apple data centers are deleted from those HSMs and instead kept entirely within the account’s iCloud Keychain protection domain. They are handled like the existing end-to-end encrypted service keys, which means Apple can no longer read or access these keys.
Advanced Data Protection also automatically protects CloudKit fields that third-party developers choose to mark as encrypted, and all CloudKit assets.
- Fundamentals of Lambda Calculus
- Functions
- Notation
- α-Conversion
- β-Reduction
- Currying — Application of multiple arguments
- Combinators
- Divergence — Never ending reduction
- Basic arithmetic in lambda calculus
- Typed lambda calculus
- References
Lambda calculus is a formal system to study computable functions based on variable binding and substitution. Introduced in the 1930s by Alonzo Church, it is (in its typed form) the fundamental concept of functional programming languages like Haskell and Scala. Although the topic might seem very theoretical, some basic knowledge in lambda calculus can be very helpful to understand these languages, and where they originated from, much better. The goal of this article is to introduce some basic concepts of lambda calculus, which later on can be mapped to real world usage scenarios with functional programming languages.
- Unlisted app distribution
Release your apps that aren’t suited for public distribution as unlisted on the App Store, discoverable only with a direct link. Unlisted apps don’t appear in any App Store categories, recommendations, charts, search results, or other listings. In addition, they can be accessed through Apple Business Manager and Apple School Manager. Apps for partner sales tools, employee resources, or research studies are examples of good candidates for unlisted distribution.
Distribute your app to:
- Limited audiences (such as part-time employees, franchisees, partners, business affiliates, higher-education students, or conference attendees) through a standard link that’s usable on the App Store and Apple School Manager or Apple Business Manager.
- Employee-owned devices that aren’t eligible to be managed through Apple School Manager or Apple Business Manager.
- Managed and unmanaged devices.
- All regions that are supported by the App Store.
- You might not need a CRDT
In developer discourse, the term CRDT sometimes gets thrown around as a synecdoche for a broader set of techniques to enable Figma-like collaborative features. But when we started talking to dozens of companies building ambitious browser-based apps, we found it rare for apps to use true CRDTs to power multiplayer collaboration.
- Prototyping SwiftUI interfaces with OpenAI's ChatGPT
Understand how to use OpenAI's ChatGPT conversational machine learning model to create working code for SwitfUI apps within a few minutes.
- Encode and decode polymorphic types in Swift
Swift’s protocol oriented programming is very helpful when dealing with polymorphic situations. But when we need to persist polymorphic data, we encounter some issues:
Codable
is not able to determine what concrete type to decode the saved data into.In this post, I will share a cut down version of the polymorphic
Codable
system that I have been using in my apps. I suggest you first take a look at my last post Reduce Codable Boilerplate with the Help of Property Wrappers that introduced how to use property wrappers in complexCodable
situations. - Native Network Monitoring In Swift
We'll take a look at a native solution for monitoring network connectivity on iOS with Swift 5 and how to use the Network Link Conditioner.
- NWPathMonitor
An observer that you use to monitor and react to network changes.
- dataTile for Simulator
Forget debugging in console
Automatically replace messy logs with beautiful visual data.
- How to manage build settings using Xcode configuration files
Xcode build configuration files are quite useful to manage configuration properties between different environments. You can also use them to easily assing a different app name and an app icon for specific environment.
- The Best Refactoring You've Never Heard Of
In physics, Feynman tells us that you cannot memorize formulas. You can't just go to the book, memorize formula, learn to apply it. There's too many of them. Instead, we need to learn about the relationships between the formulas. Derive them for yourself when they're needed.
And so, we want to do the same in programming. See many different APIs, many concepts, and see how there are fewer deeper ideas behind them. So, instead of seeing a bunch of approaches to a problem, I want you to see a web of, a single design and various ways you manipulate it to exactly the outcome that you want. So these are many transformations. Each of them could be their own talk or article. But today, I've taught you one very important transformation, not to rule them all but to rule a lot of them. And that is to, everyone with me, defunctionalize the continuation!
- Encoding and Decoding Custom Types
Make your data types encodable and decodable for compatibility with external representations such as JSON.
Many programming tasks involve sending data over a network connection, saving data to disk, or submitting data to APIs and services. These tasks often require data to be encoded and decoded to and from an intermediate format while the data is being transferred.
The Swift standard library defines a standardized approach to data encoding and decoding. You adopt this approach by implementing the Encodable and Decodable protocols on your custom types. Adopting these protocols lets implementations of the Encoder and Decoder protocols take your data and encode or decode it to and from an external representation such as JSON or property list. To support both encoding and decoding, declare conformance to Codable, which combines the
Encodable
andDecodable
protocols. This process is known as making your types codable. - We Fast-Tracked Our App Development With Kotlin Multiplatform Mobile
Motive Fleet is a mobile app available on both Android and iOS, which our customers use to access critical real time information about their fleets and drivers on the go. We are continually adding new features to Motive Fleet to enhance our customers’ experience. To execute faster and ensure consistency in business logic across our Android and iOS mobile platforms, we have been exploring mobile cross-platform tools. Our goals included easier code management, fewer bugs, better build quality, and improved development timelines—and we achieved them with Kotlin Multiplatform Mobile (KMM). Read this blog to learn:
- Advantages of a code-sharing framework
- Kotlin Multiplatform Mobile (KMM) evaluation
- Learnings & challenges from integrating KMM in our Motive Fleet app
- Impact of KMM and future work
- First Introduction to Cubical Type Theory
This page aims to present a first introduction to cubical type theory, from the perspective of a mathematician who has heard about type theory but has no previous familiarity with it. Specifically, the kind of mathematician that we are appealing to is one who is familiar with some of the ideas in category theory and homotopy theory — however, the text also presents the concepts syntactically, in a way that can be read without any prior mathematical knowledge.
- How to use a .xcconfig file and a .plist file with SPM
How to use a
.xcconfig
file and a.plist
with a Swift Package Manager based project. - Exploring the iOS Live Activities API
In this article, we’ll explore the advantages of Live Activities and the ActivityKit framework that is used for displaying and working with Live Activities. In the demo portion of the article, we’ll show how to add Live Activities to a simple stock tracking app to display real-time information on both the Lock Screen and in the Dynamic Island.
- Ruby adds a new core class called Data to represent simple immutable value objects
Ruby 3.1 adds a new core class called Data to represent simple immutable value objects. The Data class helps define simple classes for value-alike objects that can be extended with custom methods.
While the Data class is not meant to be used directly, it can be used as a base class for creating custom value objects. The Data class is similar to Struct, but the key difference being that it is immutable.
- Clean waiting in XCUITest
At Cookpad, we wanted an extension method on
XCUIElement
similar toXCTestCase.waitForExpectations(timeout:handler:)
to make tests readible, but we also have more expectations to wait for than just existence, and we didn’t want to create multiple methods to do very similar things e.g.waitUntilHittable
,waitUntilLabelMatches
etc.Additionally, we didn’t want to sleep as an expectation might occur before the timeout and we waited too long, or the opposite, and we didnt wait long enough and spent time verifying false positives. As a result, we created a solution utilising take-aways from all of the aforementioned techniques.
- Getting started with Scrumdinger
Learn the essentials of iOS app development by building a fully functional app using SwiftUI.
- SwiftUI is convenient, but slow
But I'd like to draw attention to some performance limitations, in the hope that a SwiftUI engineer might see this and understand pain points that might not be so obvious from their side.
- canDeriveCodable(NominalTypeDecl *NTD, KnownProtocolKind Kind)
Structs, classes and enums can explicitly derive Encodable and Decodable conformance (explicitly meaning we can synthesize an implementation if a type conforms manually).
- Building custom layout in SwiftUI. Basics.
Nowadays, SwiftUI provides the
Layout
protocol allowing us to build super-custom layouts by digging into the layout system without using GeometryReader.Layout
protocol brings us the incredible power of building and reusing any layout you can imagine. - An Approach for Migrating From Objective-C to Swift
- Create
Swift islands
and expand them over time. - Create shims for existing Objective-C objects to call your new Swift ones.
- Use value types within the Swift portions of your codebase, and wrap them in Objective-C compatible reference types for the Objective-C parts.
- Try to convert the ‘messaging space’ of each subsystem to Swift as early as possible, and then the messaging space between subsystems. Wrap Objective-C types that you’re not ready to tackle yet with Swift friendly interfaces. If these are working well for you, then they can stay as Objective-C on the inside for years.
- Create
- What is the @objcMembers attribute? (2019)
If you just want to expose a single method or property, you can mark that method using the
@objc
attribute. However, if you want all methods in a class to be exposed to Objective-C you can use a shortcut: the@objcMembers
keyword. - Understanding different cache policies when working with URLRequest in Swift
By choosing a cache policy, we can decide whether the caching should depend on expiration dates or disabled entirely or whether the server should be contacted to determine if the content has changed since the last request.
- Slow App Startup Times (2016)
A lot happens before the system executes your app’s main() function and calls app delegate functions like applicationWillFinishLaunching. Before iOS 10 it was not easy to understand why an app was slow to launch for reasons other than your own code. It has been possible to add the
DYLD_PRINT_STATISTICS
environment variable to your project scheme but the output was hard to figure out. With iOS 10 Apple has made the output from enablingDYLD_PRINT_STATISTICS
much easier to understand. - Diagnostic flags in Clang
This page lists the diagnostic flags currently supported by Clang.
- ObjectIdentifier
A unique identifier for a class instance or metatype.
This unique identifier is only valid for comparisons during the lifetime of the instance. In Swift, only class instances and metatypes have unique identities. There is no notion of identity for structs, enums, functions, or tuples.
- Notes for working with Xcode VIM mode
This document is a scratchpad for helping me learn commonly used actions in Xcode's VIM mode.
Commands are case-sensitive. A command of N means pressing
shift + n
on the keyboard. - Kotlin/Native as an Apple framework — tutorial
Kotlin/Native provides bi-directional interoperability with Objective-C/Swift. Objective-C frameworks and libraries can be used in Kotlin code. Kotlin modules can be used in Swift/Objective-C code too. Besides that, Kotlin/Native has C Interop. There is also the Kotlin/Native as a Dynamic Library tutorial for more information.
- The evolution of scalable CSS
A deep dive into the problems with scaling CSS on large projects. Understand the evolution of CSS best practices.
- Introduction to SwiftUI Modularisation with SPM
Today we did a brief introduction to local SPM packages and how to prepare your app for modularisation. A checklist was used to guide us in the whole process which make things easier for anyone who wants to start this endeavor.
- Why is Rosetta 2 fast?
I believe there’s significant room for performance improvement in Rosetta 2, by using static analysis to find possible branch targets, and performing inter-instruction optimisations between them. However, this would come at the cost of significantly increased complexity (especially for debugging), increased translation times, and less predictable performance (as it’d have to fall back to JIT translation when the static analysis is incorrect).
Engineering is about making the right tradeoffs, and I’d say Rosetta 2 has done exactly that. While other emulators might require inter-instruction optimisations for performance, Rosetta 2 is able to trust a fast CPU, generate code that respects its caches and predictors, and solve the messiest problems in hardware.
- XCFrameworks
This post is about how one bad assumption about XCFrameworks turned into multiple hours of needless effort. I wanted to quickly share my experience so others could avoid falling into the same pitfall. In retrospect, the problem seems obvious, but it wasn’t when I just encountered it.
- When does a SwiftUI Environment get retained?
The answer depends on how we use SwiftUI. For an app entirely written using it, one might argue that it gets released whenever the app finishes. But what about an UIKit app that uses some SwiftUI views?
- Dispose of any SwiftUI View values not used anymore
- Dispose of any UIHostingController references not used anymore
- Watch out for memory leaks in:
- UIViews used within SwiftUI
- references between your UIViews and your environment objects
- UIViewControllers presenting the UIHostingControllers
- the environment objects themselves
-
ComposableArchitecture Documentation
The Composable Architecture (TCA, for short) is a library for building applications in a consistent and understandable way, with composition, testing, and ergonomics in mind. It can be used in SwiftUI, UIKit, and more, and on any Apple platform (iOS, macOS, tvOS, and watchOS).
-
Non-exhaustive testing in the Composable Architecture
Testing is by far the #1 priority of the Composable Architecture. The library provides a tool, the TestStore, that makes it possible to exhaustively prove how your features evolve over time. This not only includes how state changes with every user action, but also how effects are executed, and how data is fed back into the system.
The testing tools in the library haven’t changed much in the 2 and a half years since release, but thanks to close collaboration with Krzysztof Zabłocki and support from his employer, The Browser Company, the 0.45.0 release of the library brings first class support for “non-exhaustive” test stores.
-
Create a bootable Ventura USB drive using Terminal
Another method to make a bootable USB drive is createinstallmedia command in Terminal.
- Rename USB Volume to MyVolume
- Now type the following command into the Terminal window:
sudo /Applications/Install\ macOS\ Ventura.app/Contents/Resources/createinstallmedia --volume /Volumes/MyVolume
-
macOS 13 Ventura Final & Beta Full Installers
This database will contain download links for macOS 13 Ventura full Installer pkg files (InstallAssistant.pkg). This file is the same full installer that you would download directly from the App Store for Intel and Apple Silicon M1 Mac Computers. The InstallAssistant.pkg is stored on Apple’s servers and contains the full “Install macOS.app”. Once downloaded, all you need to do is install the pkg and the full installer of macOS will be in your applications folder. This change was made when Apple revised the full installer for Big Sur. The InstallAssistant.pkg is not available for Catalina or Mojave.
-
Swift Concurrency - Things They Don’t Tell You
Swift Concurrency provides a really nice way of writing asynchronous code. Support for
async-await
has been to me the most awaited feature in Swift.However, with great power comes great responsibility. If you learn from tutorials or even from the documentation, it’s really hard to find some details on how it works under the hood. Basically, Swift Concurrency is advertised as safe to use, because in theory the correctness is being checked by the compiler.
This way of “selling” Swift Concurrency encourages people to just jump in, add
async-await
to an existing code, and run someTasks
not really knowing what is going on under the hood. Unfortunately, there are many traps around concurrency, and no… the compiler doesn’t check everything.To be honest, even after performing tests, reading documentation, and watching WWDC I’m still not fully confident with Swift Concurrency. Although, I will try to share with you some of my observations hopefully making you more aware.
-
Decentralized Social Networking Protocol (DSNP) specification
The free communication of users on the Internet faces a variety of problems in the modern day. These challenges include censorship from state and corporate actors, the amplification of misinformation through viral content, and an ever-shrinking collection of near monopolies with absolute power over social interaction in the twenty-first century. Through the DSNP, we hope to mitigate and ideally solve these challenges in the way social interaction operates online.
-
JavaScript is great, and by all means use it, while also being aware that you can build so many functional UI components without the additional dependancy.
Maybe you can include a few lines of utility code, or a mixin, and forgo the requirement. If you're only targeting more modern browsers, you might not need anything more than what the browser ships with.
-
Our groundbreaking security technologies protect the users of over 1.8 billion active devices around the world. Hear about the latest advances in Apple security from our engineering teams, send us your own research, and work directly with us to be recognized and rewarded for helping keep our users safe.
-
Starting with Xcode 14, when you create a new iOS project, the app icon in the asset catalog defaults to the new “Single Size”. Instead of the full set of icon sizes there’s a single slot for a 1024×1024 point image that the system resizes as needed.
-
Swift Concurrency — Things They Don’t Tell You
Swift Concurrency provides a really nice way of writing an asynchronous code. Support for async-await has been to me the most awaited feature in Swift.
However, with great power comes great responsibility. If you learn from tutorials or even from the documentation, it’s really hard to find some details on how it works under the hood. Basically, Swift Concurrency is advertised as safe to use, because in theory the correctness is being checked by the compiler.
This way of “selling” Swift Concurrency encourages people to just jump in, add async-await to an existing code, and run some Tasks not really knowing what is going on under the hood. Unfortunately, there are many traps around concurrency and no… the compiler doesn’t check everything.
To be honest, even after performing tests, reading documentation, and watching WWDC I’m still not fully confident with Swift Concurrency. Although, I will try to share with you some of my observations hopefully making you more aware.
-
The
swift-driver
project is a new implementation of the Swift compiler driver that is intended to replace the existing driver with a more extensible, maintainable, and robust code base. The specific goals of this project include:- A maintainable, robust, and flexible Swift code base
- Library-based architecture that allows better integration with build tools
- Leverage existing Swift build technologies (SwiftPM, llbuild)
- A platform for experimenting with more efficient build models for Swift, including compile servers and unifying build graphs across different driver invocations
-
The Swift Driver, Compilation Model, and Command-Line Experience
The Swift compiler's command-line interface resembles that of other compilers, particularly GCC and Clang. However, Swift's compilation model and some of its language features make it a bit tricky to plug into a larger build system. In particular, there's no correct way to specify a "one command per file" build rule for a normal Swift module.
-
Swift Driver Design & Internals
This document serves to describe the high-level design of the Swift 2.0 compiler driver (which includes what the driver is intended to do, and the approach it takes to do that), as well as the internals of the driver (which is meant to provide a brief overview of and rationale for how the high-level design is implemented).
The Swift driver is not intended to be GCC/Clang compatible, as it does not need to serve as a drop-in replacement for either driver. However, the design of the driver is inspired by Clang's design
-
Swift Driver Parseable Driver Output
This document serves to describe the parseable output format provided by the Swift compiler driver with the "-parseable-output" flag. This output format is intended to be parsed by other programs; one such use case is to allow an IDE to construct a detailed log based on the commands the driver issued.
-
iOS Ref was created in January 2018 by me to serve as a one-stop quick reference spot for iOS developers.
-
Where View.task gets its main-actor isolation from
SwiftUI’s
.task
modifier inherits its actor context from the surrounding function. If you call.task
inside a view’sbody
property, the async operation will run on the main actor becauseView.body
is (semi-secretly) annotated with@MainActor
. However, if you call.task
from a helper property or function that isn’t@MainActor
-annotated, the async operation will run in the cooperative thread pool. -
Developer guide on the iOS file system
Learn how to work with files and directories when developing iOS applications.
In this developer guide, we'll look at the organisation of APFS and the rules that apply to our code when we develop iOS applications.
-
See the architecture of any codebase!
Codeface visualises the internal composition, dependencies and quality metrics of code to help you understand, improve and monitor it.
-
Check if two values of type Any are equal
In Swift 5.7 that comes with Xcode 14 we can more easily check if two values of type
Any
are equal, because we can cast values toany Equatable
and also useany Equatable
as a parameter type thanks to Unlock existentials for all protocols change. -
@StateObject
vs.@ObservedObject
: The differences explained@StateObject
and@ObservedObject
have similar characteristics but differ in how SwiftUI manages their lifecycle. Use the state object property wrapper to ensure consistent results when the current view creates the observed object. Whenever you inject an observed object as a dependency, you can use the@ObservedObject
.Observed objects marked with the
@StateObject
property wrapper don’t get destroyed and re-instantiated at times their containing view struct redraws. Understanding this difference is essential in cases another view contains your view. -
Swift was always going to be part of the OS
Recently on the Swift Forums, someone complained that putting Swift in the OS has only made things worse for developers. My immediate reaction is a snarky “welcome to the world of libraries shipped with the OS”, but that’s not helpful and also doesn’t refute their point. So here’s a blog post that talks about how we got where we did, covering time when I worked on Swift at Apple. But I’m going to have to start a lot earlier to explain the problem…
-
Dynamic Linking Is Bad For Apps And Static Linking Is Also Bad For Apps
A recent question on the Swift forums prompted me to actually write this blog post I’ve been idly thinking about for a long time. These days, it’s common for apps to have external dependencies, but both statically linking and dynamically linking those dependencies comes with drawbacks. (This is the same thing as the title, only less provocative.) Why is there this tension and what can be done about it?
-
[unsafeFlags(::)](https://developer.apple.com/documentation/packagedescription/swiftsetting/unsafeflags(_:_:)
Set unsafe flags to pass arbitrary command-line flags to the corresponding build tool.
e.g
swiftSettings: [.unsafeFlags(["-Xfrontend", “-enable-bare-slash-regex”])]
-
Mastering NavigationStack in SwiftUI. NavigationPath.
Today we learned how to use the NavigationPath type to push different views programmatically without defining additional types. We also learned how to serialize and store the current state of navigation in the scene storage to provide a better user experience.
-
withThrowingTaskGroup(of:returning:body:)
Starts a new scope that can contain a dynamic number of throwing child tasks.
-
The new standard for interactive graphics
Blazing fast. Tiny size. Runs everywhere.
- Universals to the right, Existentials to the left: the adjoint triple "Exists ⊣ Const ⊣ Forall"
Exists @k ⊣ Const @k ⊣ Forall @k
- How To Deploy a Kotlin API With http4k and Heroku
This guide describes how to generate a Kotlin API using the http4k Project Wizard, and goes over what configurations and steps you'll need in order to deploy it (and other Kotlin APIs) to Heroku.
- TCA Action Boundaries
As I described in the exhaustivity testing article, a larger scale usually means discovering issues you might not have experienced with smaller apps. I'll cover more of them and my suggested solutions shortly, but today, I want to talk about Actions, their lack of boundaries, and what it entails.
- DynamicIsland
The layout and configuration for a Live Activity that appears in the Dynamic Island.
- SwiftUI Navigation & URL Routing — Brandon Williams
After a brief overview of how SwiftUI's new NavigationStack API works, we'll explore how to build a router that can transform nebulous URLs into state that drives deep-linking in your application. Then, almost magically, that same code will be used to power a server-side application for generating deep-linking URLs.
- How to Use an Infrared Sensor With the Raspberry Pi Pico
How can one use an infrared sensor with the Raspberry Pi Pico? With Raspberry Pi rolling out the all new Raspberry Pi Pico now, this is a rather common query for makers.
An infrared sensor is a sensor that can measure the infrared light / electromagnetic radiation emitted by an object thereby detecting its presence. In this blog, we shall take a look at writing a program to use an infrared sensor with the Raspberry Pi Pico.
- Nate's adjoint 5-tuple
In August, Nate Soares visited Topos Institute. We told him a little about
Poly
andProly
Proly and he told us about what he wanted from a type theory. - Mastering Dynamic Island in SwiftUI
In this post, we will discuss possible configurations and customization points of the dynamic island feature using the new API available in the WidgetKit framework.
- Live Activities (HUD)
A Live Activity displays up-to-date information from your app, allowing people to view the progress of events or tasks at a glance.
Live Activities help people keep track of tasks and events that they care about, offering persistent locations for displaying information that updates frequently. For example, a food delivery app could display the time remaining until a food order arrives, or a sports app can display the score for an ongoing game.
- Polynomial functors and lenses
The category of polynomial functors is the free coproduct completion of Setsop. Equivalently, it is the total space of the family fibration of Setsop. More concretely, an object of Poly is given by a set I and a family of sets
A:I→Sets
. - The iOS Engineer’s Guide to Beginning Kotlin Multiplatform Development
- One of the most essential skills for Kotlin Multiplatform Mobile cross-platform development is sensitivity to what code is platform-dependent or not.
- Platform-dependent code can be written entirely in Kotlin using KMM’s expect and actual syntax or by defining an interface in the KMM common module and implementing it natively in Android (using Kotiln) and iOS (using Swift).
- Platform-independent code is written inside the KMM shared framework and can be used for any business logic for your application that does not directly depend upon any platform-specific code.
- Given the complexities of writing multi-platform code, this post provides an overview, and future posts will dive deeper into these topics.
- Displaying live activities in iOS 16
One of the most prominent features of iOS 16 is live activity widgets. iOS 16 allows us to display the live state of ongoing activities from our apps on the lock screen or in the Dynamic Island of the new iPhone 14 Pro. This week we will learn how to build live activity widgets for our apps using the new ActivityKit framework.
- Simplify Your React Component’s State With a State Machine
Use a reducer to implement a fully-typed state machine without breaking a sweat.
- Composable Architecture @ Scale
Last week I spoke at NSSpainX to talk about how to use Composable Architecture in larger projects, the kind of issues you might run into and how you can work around them.
Roughly: tags, IDs (thrice), limits, pagination.
After using AWS for ~14 years, I've internalised a handful of design patterns that I try to apply to my own software. I'm keen to know if it's the same for other folks.
- SwiftUI's diffing algorithm
- Unary views: Views with a single displayable, such as shapes, colors, controls and labels.
- Structural views: Views that take zero or more other views, and combines them into a view with some subset of their displayables. Examples:
ForEach
,EmptyView
, and the views used byViewBuilder
, such asTupleView
and_ConditionalView
. - Container views: Views that take the displayables of another view and manage them by deciding whether they should be displayed and how they should be laid out. Examples:
HStack
,VStack
,List
,LazyVStack
. - Modifiers: Views that take one other view, and change the layout or look of all of its displayables individually. Examples: the views that modifiers such as
.border
,.padding
,.frame
generate, which are of typeModifiedContent
.
- What's the "any" keyword? Understanding Type Erasure in Swift
The concept of Type Erasure is not new to Swift, but was radically improved in Swift 5.7 with the addition of the any prefix keyword (not to be confused with the capitalized Any type!) and improvements to the already existing some Opaque Type keyword. In this article, we'll explain the concept of type erasure, how it used to be done, what's different in Swift 5.7, and how these changes work under the hood.
- A functional (programming) approach to error handling in Typescript
Typescript and Javascript provide an error handling strategy based on the try/catch syntax which allows the programmer to escape the normal flow of the program in the presence of errors. This way of doing error handling certainly does its job but there are drawbacks that are often just accepted without giving too much thought about it. In this post, I will detail what these drawbacks are and how some ideas from functional programming can help to overcome them.
- Using generics in Arrow functions in TypeScript
const returnInArray = <T>(value: T): T[] => [value];
- Domain Driven Design using GADTs
We used this approach in aws-lambda-haskell-runtime. Since Lambda results and errors must have a differently formatted body depending on the proxy (API Gateway, ALB, etc.), we used GADTs to make illegal states unrepresentable.
- How 5 iOS apps could improve their startup time by an average of 28%
Milliseconds matter
Startup time is a crucial app metric that should be continuously monitored and improved. A/B tests at top mobile app companies consistently show that adding just fractions of a second can significantly hurt core usage metrics, such as daily active users and time spent on the app per user per day.
Lyft reported a 5% increase in user sessions thanks to a 21% decrease in startup time for their driver app. Apple has made startup time the subject of numerous WWDC presentations.
- Cancel or change the payment method for your AppleCare plan
Make changes to your AppleCare+ plan or AppleCare Protection Plan.
If you paid in full upfront for your AppleCare plan
- The AppleCare agreement number. Sign in to MySupport to look up your agreement number.
- The serial number of the device that the plan covers. Learn how to find the serial number.
- Your original sales receipt.
- The SwiftUI Layout Protocol – Part 1
One of the best SwiftUI additions this year has to be the Layout protocol. Not only we finally get our hands in the layout process, but it is also a great opportunity to better understand how layout works in SwiftUI.
Creating a basic layout is not hard, we just need to implement two methods. Nevertheless, there are a lot of options we can play with to achieve more complex containers. We will explore beyond the typical Layout examples. There are some interesting topics I haven’t seen explained anywhere yet, so I will present them here. However, before we can dive into these areas, we need to begin by building a strong foundation.
- The SwiftUI Layout Protocol – Part 2
In the first part of this post we explored the basics of the Layout protocol in order to build a strong foundation of how Layout works. Now it’s time to dive into the less commented features and how to use them in our benefit.
- About firmware updates for AirPods
Learn about changes and features included in the firmware updates for your AirPods.
- TIL: You Can Access A User’s Camera with Just HTML
You can put the
capture
attribute on inputs with the type of file, and you can give it a value of “user
” or “environment
“.The interesting thing about the capture attribute is for users coming to your website on a mobile device. If they interact with that input, instead of opening up the default file picker, it will actually open up one of their cameras. It could be the front facing camera or the back facing camera, depending on the value.
If you set the value to “
user
“, it will use the user facing or front facing camera and or microphone. And if you set it to “environment
“, it will use the outer facing or back facing camera and or microphone. - Exploring SwiftUI Redraw Behavior with Instruments
- Be careful using the
@ObservedObject
in all your views, use it only when it is needed. - It is not because is working that your code is optimal.
- While working with SwiftUI check what views are redrawing with Instruments and if all your redraws are intended.
- Be careful using the
- Improving Composable Architecture performance
We are always looking for ways to improve the performance of our Composable Architecture, and spurred by some fascinating recent discussions, we spent most of last week looking for performance wins in the library. This has all culminated in a new release, 0.40.0, which brings a number of improvements to the library, and best of all, most of the changes came from collaboration with people in the community! 🤗
- How Much Does An Average App Development Cost In 2022?
So, the question arises, how much does it cost to develop an app for my business?
What should my budget be? It seems like it fluctuates all the time. To put things in perspective, a recent study by Clutch of 12 top app developers found that the cost to create a mobile app ranged from $30,000 to $700,000.
Let us understand more about app development costs. It would help if you asked the right questions to fix your budget and start developing an app after you hire a developer!
- Steve Jobs Archive
I grow little of the food I eat, and of the little I do grow I did not breed or perfect the seeds.
I do not make any of my own clothing.
I speak a language I did not invent or refine.
I did not discover the mathematics I use.
I am protected by freedoms and laws I did not conceive of or legislate, and do not enforce or adjudicate.
I am moved by music I did not create myself.
When I needed medical attention, I was helpless to help myself survive.
I did not invent the transistor, the microprocessor, object oriented programming, or most of the technology I work with.
I love and admire my species, living and dead, and am totally dependent on them for my life and well being.
Sent from my iPad
- safeAreaAspectFitLayoutGuide
A layout guide for placing content of a particular aspect ratio.
This layout guide provides a centered region in the window where you can place media content of a particular aspect ratio (width over height) to avoid obscuring the content.
- JSON Crack
Seamlessly visualize your JSON data instantly into graphs.
- Three UIKit Protips
There are three patterns I use in most of my UIKit projects that I've never seen anyone else talk about. I think they help readability a lot, so I'm sharing them here:
- An
addSubviews
method to define your view hierarchy all at once - An
@AssignedOnce
property wrapper - A pattern for keeping view creation at the bottom of a file to keep the top clean
- An
- Using CoordinateSpace to draw over a SwiftUI List
In
UIKit
, we would useUICoordinateSpace.convert(_,to:)
or the olderUIView.convert(_,to:)
functions, and happily there's a SwiftUI equivalent inCoordinateSpace
. - Create Live Activities With ActivityKit on iOS 16
We will use SwiftUI and WidgetKit to create the user interface of the Live Activity. Live Activities works like Widget Extension and enables code sharing between your widgets and Live Activities.
- Sharing cross-platform code in SwiftUI apps
The biggest issue when working on a cross-platform SwiftUI app is when you need to drop into AppKit on macOS and UIKit on iOS. Often, the APIs that you need (because they are absent from SwiftUI) are simply entirely different. However, sometimes the APIs are nearly identical but just different enough to require branching into platform-specific code paths. A good example of this is
UIPasteboard
on iOS andNSPasteboard
on macOS. - Xcode's refactoring options for async/await
Automatically adopt async functions in your codebase with ease
- Sourcery Swift Package command plugin
In this article I will be covering what a Sourcery command plugin looks like, but I am already working on a part two where I will be creating a build tool plugin, which presents numerous interesting challenges.
-
Here is an exhaustive, annotated list of GHCi commands, somewhat divided by task. Within each section, commands are listed alphabetically.
Some important ones are covered in more detail in their own lessons. Each command is linked to the page in this course that discusses it; you can either click through to find out about a particular command of interest, or keep reading through this series to get to it.
-
@ViewBuilder usage explained with code examples
The
@ViewBuilder
attribute is one of the few result builders available for you to use in SwiftUI. You typically use it to create child views for a specific SwiftUI view in a readable way without having to use any return keywords. -
Adjust the direction of focus-based navigation in SwiftUI
When the user navigates through focusable views in our app with the tab key, the focus will move in the reading order: first from the leading edge to the trailing edge and then from top down. While this default behavior is right for many use cases, sometimes we need to customize and redirect the focus movement to fit our custom app design.
-
Responsive layout in SwiftUI with ViewThatFit
Making SwiftUI views responsive usually involves a lot of
GeometryReaders
andif-else
.In iOS 16, SwiftUI got a new view that makes it easier to create a responsive layout,
ViewThatFits
.ViewThatFits
applyfixedSize()
on each child view, starting from the top.- If the child view ideal size is larger than the parent's proposed size,
ViewThatFits
evaluate the next child. - Then it returns the first child that fits within the proposed size.
-
Well, not like Carbon. Don’t be so dramatic!
More like Core Foundation. It’s still there behind the scenes, but programmers use high-level Objective-C and Swift wrappers from Foundation. If something is missing, you can call an underlying C API. The relation between SwiftUI and AppKit is similar, for now.
-
Migrating to protocol reducers (TCA)
Learn how to migrate existing applications to use the new ReducerProtocol, in both Swift 5.7 and Swift 5.6.
Migrating an application that uses the Reducer type over to the new ReducerProtocol can be done slowly and incrementally. The library provides the tools to convert one reducer at a time, allowing you to plug protocol-style reducers into old-style reducers, and vice-versa.
Although we recommend migrating your code when you have time, the newest version of the library is still 100% backwards compatible with all previous versions. The Reducer type is now "soft" deprecated, which means we consider it deprecated but you will not get any warnings about it. Some time in the future we will officially deprecate it, and then sometime even later we will remove it so that we can rename the protocol to Reducer.
-
The Composable Architecture Performance
Learn how to improve the performance of features built in the Composable Architecture.
As your features and application grow you may run into performance problems, such as reducers becoming slow to execute, SwiftUI view bodies executing more often than expected, and more.
- View stores
- CPU-intensive calculations
- High-frequency actions
-
Stop Xcode 14 beta from draining your battery
There's a bug in Xcode 14 betas 4-6 that causes a crash loop in the PosterBoard process when you run an iOS 16 iPhone simulator, making your computer's CPU usage go sky high and battery to drain very quickly. Here's a workaround until Apple resolves the issue.
-
How to Make Custom Test Assertions in Swift (2016)
Here are the steps for creating specialized test assertions in Swift:
- Define your assertion as a helper function.
- Design the parameters to be unambiguous.
- Include optional parameters for file and line.
- Upon failure, call XCTFail, passing the file and line arguments.
- Report all the information you need to diagnose failures.
- Can you make the assertion generic?
-
How to bridge async/await functions to Combine's Future type in Swift
Learn how to call async/await code within Combine based APIs.
-
func withLock<R>(_ body: () throws -> R) rethrows -> R
-
Keeping a widget up to date efficiently on iOS
- Make use of timelines
- Find ways to refresh when appropriate
- Make use of caching
-
The Best and Fastest Ways to Install Xcode on your Mac
In this article, we will look at all of the alternative ways to install Xcode, how to speed up the process, and how to resolve disk space problems. We’ll also look at the Windows alternative to Xcode.
-
Structural identity in SwiftUI (2021)
Structural identity is the type of identity that SwiftUI uses to understand your views without an explicit identifier by using your layout description. This week we will learn how to improve performance and eliminate unwanted animations by using inert view modifiers in SwiftUI.
-
You have to change mindset to use SwiftUI (2019)
Last week I saw that the community tries to move UIKit development patterns to SwiftUI. But I’m sure that the best way to write efficient SwiftUI is to forget everything about UIKit and entirely change your mindset in terms of User Interface development. This week we will learn the main differences between UIKit and SwiftUI development.
-
The supported platforms for running Swift on the server and the ready-built tools packages are all hosted here on swift.org together with installation instructions. There’s also the language reference documentation section for viewing more information about Swift.
-
The recommended way to build server applications is with Swift Package Manager. SwiftPM provides a cross-platform foundation for building Swift code and works nicely for having one code base that can be edited as well as run on many Swift platforms.
-
SwiftPM is integrated with XCTest, Apple’s unit test framework. Running swift test from the terminal, or triggering the test action in your IDE (Xcode or similar), will run all of your XCTest test cases. Test results will be displayed in your IDE or printed out to the terminal.
-
First of all, it’s very important to make sure that you compiled your Swift code in release mode. The performance difference between debug and release builds is huge in Swift. You can compile your Swift code in release mode using
swift build -c release
. -
Deploying to Servers or Public Cloud
The following guides can help with the deployment to public cloud providers:
- AWS on EC2
- AWS on Fargate with Vapor and MongoDB Atlas
- DigitalOcean
- Heroku
- Kubernetes & Docker
- GCP
- Have a guides for other popular public clouds like Azure? Add it here!
-
Packaging Applications for Deployment
Once an application is built for production, it still needs to be packaged before it can be deployed to servers. There are several strategies for packaging Swift applications for deployment.
-
For multithreaded and low-level unsafe interfacing server code, the ability to use LLVM’s ThreadSanitizer and AddressSanitizer can help troubleshoot invalid thread usage and invalid usage/access of memory.
-
Structs, Classes, and Actors in iOS Interviews
We saw what are reference and value types, and what are the new actor types. Also, we described some reasons to use classes over structs and what is dynamic and static methods dispatch in Swift. We discussed thread safety using types in Swift and how you can expand your studies about them.
-
Conditional layouts in SwiftUI
From the first day of the SwiftUI framework, we have primary layout containers like VStack, HStack, and ZStack. The current iteration of the SwiftUI framework brings another layout container allowing us to place views in a grid. But the most important addition was the Layout protocol that all layout containers conform to. It also allows us to build our super-custom layout containers from scratch. This week we will learn the basics of the Layout protocol in SwiftUI and how to build conditional layouts using AnyLayout type.
-
The LDT, a Perfect Home for All Your Kernel Payloads
The concepts presented here highlight several powerful generalized techniques for macOS kernel exploits on Intel-based systems. We demonstrated how the dblmap can substantially weaken the efficacy of KASLR, provide several interesting kernel call targets, host smuggled kernel shellcode, and more.
These primitives were used in the practical exploitation of numerous kernel vulnerabilities we responsibly disclosed to Apple over the past year. Abusing core low-level constructs of the operating system can lead to very interesting consequences, and prove incredibly challenging to mitigate.
-
An Application for Inspecting macOS Installer Packages
-
withUnsafeTemporaryAllocation(of:capacity:_:)
Provides scoped access to a buffer pointer to memory of the specified type and with the specified capacity.
-
Swiftinit is a collection of richly-linked high-level technical articles and tutorials related to the Swift programming language. Kelvin Ma started Swiftinit in late 2021 when he and a few professional Swift developers realized that educational resources for the Swift language were often scattered across personal blogs or buried deep in Github repositories, making it hard to beginners to get started with the language.
-
View Controller Presentation Changes in iOS and iPadOS 16
In iOS/iPadOS 16.0 there have been a few minor and one significant change in behaviour when presenting modal view controllers:
- when the presenting view controller is in a regular-width environment on iPad, form sheets are slightly bigger than on previous iPadOS versions. This changed in beta 4. (If the presenting view has compact width, a form sheet presentation will adapt and fill the width, just like on iPhone.)
- the height of the navigation bar in a non-full-screen, non-popover, modally-presented view controller is smaller than before (12 points smaller on iPhone and 6 points smaller on iPad). This change has only just occurred in beta 5. Many thanks to Jordan Hipwell for discovering this and bringing it to my attention. He also discovered this has not (yet?) changed in SwiftUI.
- non-full-screen modally-presented double and triple column style split view controllers have a different appearance compared to iPadOS 13 to 15.
-
Achieving A Completely Open Source Implementation of Apple Code Signing and Notarization
I'm very excited to announce that we now have a pure Rust implementation of a client for Apple's Notary API in the apple-codesign crate. This means we can now notarize Apple software from any machine where you can get the Rust crate to compile. This means we no longer have a dependency on the 3rd party Apple Transporter application. Notarization, like code signing, is 100% open source Rust code.
-
An Introduction to Plutus Core
Plutus Core (PLC) is the programming language that “runs” on the Cardano Blockchain. A blockchain is just a distributed data structure though, so programs do not literally run on it. What we mean is that Plutus Core programs are stored on the blockchain in binary form and can be referenced by transactions. Plutus Core programs are later retrieved from the blockchain and executed by Cardano Nodes when required by other transactions that reference them.
In this blog post, we give a high-level overview of the role that Plutus Core plays in the Cardano ecosystem, what programs written in Plutus Core look like, and how those programs work.
-
Stabilize, Modularize, Modernize: Scaling Slack’s Mobile Codebases
The Stabilization phase of Project Duplo lasted six months. In this phase, we wanted to “stop the bleeding”, by addressing key elements of tech debt that were slowing development on each platform. We talked to our mobile developers about the issues they thought were the most important to address, used code health metrics to assess which files in the codebase were the “worst”, and tried to focus on a few key areas where we could make big impacts. For this phase, we had a core team of developers who were dedicated to working on Duplo, as well as leads for each platform. This core team worked together throughout the Stabilization phase, to ensure we had developers focused on the project (and not pulled off onto feature development).
-
Scaling Slack’s Mobile Codebases: Modularization
We use the word
module
to describe a subproject — generally a static or dynamic framework linked into the app. Prior to Duplo, we had split off some of our infrastructure code into subprojects on both platforms, but most of the code was still in the main app target, and all feature development was happening there. During Duplo, modularization was a key focus of the project, and we made a concerted push to move code out of the app target. -
Scaling Slack’s Mobile Codebases: Modernization
In addition to modularizing our codebase as part of Duplo, we also wanted to improve our overall app architecture, ensure we were keeping up with industry trends, and adopt more forward-looking design patterns and technologies. On each platform, we decided on particular areas of focus which we thought would both improve the experience of building features for our mobile developers and put our mobile codebases on better footing.
-
Experimenting with Live Activities
"These are my notes on playing with the API and implementing my first Live Activity."
-
How do 3D transforms of iOS views work under the hood?
When it comes to transforming a view, one can think of it as applying a calculation to each individual point of the view’s layer, such that for every
(x, y, z)
, we obtain a new(x', y', z')
. That calculation is actually a multiplication of the coordinates(x, y, z)
by a matrix (good ol' linear algebra). How we construct our matrix is through the use of various types of CATransform3Ds, which we’ll now dive into. -
TIL: lldb po strongly captures an object, forever
While investigating some memory leak issue, I found out that if I po an object before using Memory Graph, that object would stay in memory forever, and Memory Graph would show something like NSKeyValueDependencyInfo as an owner of the object.
A leak will also happen when using
p
orexpression
. -
A comparator that uses another sort comparator to provide the comparison of values at a key path.
-
Sort elements based on a property value using KeyPathComparator
If we have an array of elements in Swift and we need to sort it based on a specific property, we can't use the simple sorted() method.
Another way to approach it would be to use KeyPathComparator introduced in Foundation in iOS 15. We can pass the comparator created with a key path to a particular property to sorted(using:) method.
-
Sendable and @Sendable closures explained with code examples
Sendable and @Sendable are part of the concurrency changes that arrived in Swift 5.5 and address a challenging problem of type-checking values passed between structured concurrency constructs and actor messages.
- Monad Confusion and the Blurry Line Between Data and Computation
There's a common joke that the rite of passage for every Haskell programmer is to write a "monad tutorial" blog post once they think they finally understand with how they work. There are enough of those posts out there, though, so I don't intend for this to be yet another monad tutorial. However, based on my learning experience, I do have some thoughts on why people seem to struggle so much with monads, and as a result, why so many of those tutorials exist.
At a high level, the intuition for monads are that they are an abstraction of sequencing in programming. Any computation that involves "do this, and then do that using the previous result" can be considered monadic.
- Common Swift Task Continuation Problem
One thing that the Swift engineering community thought when they were developing the new asynchronous API is that in some manner they should support a bridging way to connect your old closure-based APIs with the new async/await world.
And that is exactly what they did, the Swift team created the Continuation API. This creates a suspension point in your code and that is exactly what you need to use the new async/await semantics.
- UI Design Difference between Android and IOS Apps
The design brings excellent user/client experience for Android and iOS development. The two platforms have different explicit highlights in their UI/UX approach. Yet, both have predictable highlights that guarantee the user a better experience.
But Apple, they try to have complete command over their items. It guarantees that the client has a reliable encounter with any of the gadgets of Apple’s. Apple takes more care of the design, UX, and exhibitions than different makers. But Google they have a platform that targets a significant part of accessible phones.
I’d like to highlight the UI differences between Android and iOS on various prospects.
- ActivityKit
Share live updates from your app as Live Activities on the Lock Screen.
With the ActivityKit framework, you can start a Live Activity to share live updates from your app on the Lock Screen. For example, a sports app might allow the user to start a Live Activity for a live sports game. The Live Activity appears on the Lock Screen for the duration of the game and offers the latest updates about the game at a glance.
In your app, you use ActivityKit to configure, start, update, and end the Live Activity, and your app’s widget extension uses SwiftUI and WidgetKit to create the user interface of the Live Activity. This makes the presentation code of a Live Activity similar to the widget code and enables code sharing between your widgets and Live Activities. However, Live Activities use a different mechanism to receive updates compared to widgets. Instead of using a timeline mechanism, Live Activities receive updated data from your app with ActivityKit or by receiving remote push notifications with the User Notifications framework.
- Displaying live data on the Lock Screen with Live Activities
Start a Live Activity that appears on the Lock Screen and update it with your app’s most current data.
Live Activities display and update an app’s most current data on the iPhone Lock Screen. This allows people to see live information they care about the most at a glance. To offer Live Activities, add code to your existing widget extension or create a new widget extension if your app doesn’t already include one. Live Activities use WidgetKit functionality and SwiftUI for their user interface on the Lock Screen. ActivityKit’s role is to handle the life cycle of each Live Activity: You use its API to request, update, and end a Live Activity.
- Activity
The object you use to start, update, and end a Live Activity.
- TYPE-SIGNATURE
It's basically
"Who Wants to Be a Millionaire?"
— but with types. - NavigationSplitView
A view that presents views in two or three columns, where selections in leading columns control presentations in subsequent columns.
You create a navigation split view with two or three columns, and typically use it as the root view in a Scene. People choose one or more items in a leading column to display details about those items in subsequent columns.
- Format Styles In Excruciating Detail
Swift’s FormatStyle and ParseableFormatStyle are the easiest way to convert Foundation data types to and from localized strings. Unfortunately Apple hasn’t done a great job in documenting just what it can do, or how to use them.
- LabeledContent
A container for attaching a label to a value-bearing view.
- Mastering LabeledContent in SwiftUI
LabeledContent view is a simple view that composes a label and content. Usually, it displays the label on the leading edge and the content on the trailing edge. You can achieve similar behavior by inserting the label and content into the HStack and placing the Spacer view between them.
- From Strings to Data Using ParsableFormatStyle
The venerable (NS)Formatter class (and Apple’s various subclasses) are an Objective-C based API that is most well known as the go-to method for converting data types into strings. One of the lesser-known features of the APIs are that these same formatters can do the reverse: parse strings into their respective data types.
Apple’s modern Swift replacement system for Formatter is a set of protocols: FormatStyle and ParseableFormatStyle. The former handles the conversion to strings, and the latter strings to data.
FormatStyle and it’s various implementations is it’s own beast. Apple’s various implementations to support the built-in Foundation data types is quite extensive but spottily documented. I made a whole site to help you use them.
But that’s not what we’re going to talk about today.
Today we’re going to talk about ParseableFormatStyle and it’s implementations. How can we convert some strings into data?
- Supporting FormatStyle & ParseableFormatStyle To Your Custom Types
A full example of adding String and AttributedString output to our custom types, as well as adding the ability to parse String values into your custom type.
- Formatting Your Own Types
So you’ve read the gosh darn site and know how to get strings from data types.. Then you read the ParseableFormatStyle post and know how to parse strings into data. If your next thought was: “Now I want to do this with my own data types”, then this is for you.
- Switching between SwiftUI’s HStack and VStack
SwiftUI’s various stacks are some of the framework’s most fundamental layout tools, and enable us to define groups of views that are aligned either horizontally, vertically, or stacked in terms of depth.
struct DynamicStack<Content: View>: View {
var horizontalAlignment = HorizontalAlignment.center
var verticalAlignment = VerticalAlignment.center
var spacing: CGFloat?
@ViewBuilder var content: () -> Content
var body: some View {
currentLayout(content)
}
}
private extension DynamicStack {
var currentLayout: AnyLayout {
switch sizeClass {
case .regular, .none:
return horizontalLayout
case .compact:
return verticalLayout
@unknown default:
return verticalLayout
}
}
var horizontalLayout: AnyLayout {
AnyLayout(HStack(
alignment: verticalAlignment,
spacing: spacing
))
}
var verticalLayout: AnyLayout {
AnyLayout(VStack(
alignment: horizontalAlignment,
spacing: spacing
))
}
}
import SwiftUI
/// Edit: I completely refactored the code. The previous implemenation is accessible through
/// revisions. Now:
/// ```
/// let path = NavigationPath()
/// let inspectable: NavigationPath.Inspectable = path.inspectable //or
/// let typedInspectable: NavigationPath.Inspectable.Of<Component>
/// = path.inspectable(of: Component.self)
/// ```
/// Both types are random-access and range replaceable collections. The first one of Any?, the
/// second of `Component`.
/// Both expose a `.navigationPath` property, so it is easy to construct a Binding like
/// ```
/// @State var path = NavigationPath().inspectable
/// NavigationStack(path: $path.navigationPath) { … }
/// ```
/// All of the following is enabled by our capacity to extract the last path component. It is maybe
/// possible to defer this function to SwiftUI by observing what's popping up in
/// `.navigationDestination`, but it is unlikely that we'll be able to make this work without
/// glitches/side-effects.
/// So for now, we are restricted to `NavigationPath`with `Codable` components only.
///
/// As an aside, I find very interesting that once you have `var count: Int`, `var last: Element?`,
/// `append(Element)` and `removeLast()` operations on a set of elements, you can turn it into a
/// mutable random access collection.
// MARK: - Common Helpers -
extension NavigationPath { // RandomAccessCollection-like
var _startIndex: Int { 0 }
var _endIndex: Int { count }
/// We opt in for throwing functions instead of subscripts. This also makes room for an
/// hypothetical `inout` cache argument.
func get(at position: Int) throws -> Any {
var copy = self
copy.removeLast(count - (position + 1))
return try copy.lastComponent!
}
mutating func set(_ newValue: Any, at position: Int) throws {
// Auto-register the mangled type name
registerValueForNavigationPathComponent(newValue)
// We preserve the tail (position+1)...
var tail = [Any]()
while count > position + 1 {
// Because `lastComponent == nil <=> isEmpty`, we can force-unwrap:
tail.append(try lastComponent!)
removeLast()
}
// Discard the one that will be replaced:
if !isEmpty {
removeLast()
}
// Double parenthesis are required by the current version of Swift
// See https://github.com/apple/swift/issues/59985
append((newValue as! any (Hashable & Codable)))
// Restore the tail that was preserved:
for preserved in tail.reversed() {
append((preserved as! any (Hashable & Codable)))
}
}
}
extension NavigationPath { // RangeReplaceableCollection+MutableCollection-like
mutating func _replaceSubrange<C>(_ subrange: Range<Int>, with newElements: C) throws
where C : Collection, Any == C.Element {
// Auto-register the mangled type name
if let first = newElements.first {
registerValueForNavigationPathComponent(first)
}
// We apply the same trick than for the index setter.
var tail = [Any]()
while count > subrange.upperBound {
tail.append(try lastComponent!)
removeLast()
}
// We don't need to preserve this part which will be replaced:
while count > subrange.lowerBound {
removeLast()
}
// Insert the new elements:
for newValue in newElements {
append((newValue as! any (Hashable & Codable)))
}
// Restore the preserved tail:
for preserved in tail.reversed() {
append((preserved as! any (Hashable & Codable)))
}
}
}
extension NavigationPath {
public struct Inspectable: RandomAccessCollection, RangeReplaceableCollection, MutableCollection {
public var navigationPath: NavigationPath
public init(_ navigationPath: NavigationPath) {
self.navigationPath = navigationPath
}
public init() {
self.navigationPath = .init()
}
public var startIndex: Int { navigationPath._startIndex }
public var endIndex: Int { navigationPath._endIndex }
public subscript(position: Int) -> Any {
get {
do {
return try navigationPath.get(at: position)
} catch {
NavigationPath.printExtractionError(error)
}
}
set {
do {
try navigationPath.set(newValue, at: position)
} catch {
NavigationPath.printExtractionError(error)
}
}
}
public mutating func replaceSubrange<C>(_ subrange: Range<Int>, with newElements: C)
where C : Collection, Any == C.Element {
do {
try navigationPath._replaceSubrange(subrange, with: newElements)
} catch {
NavigationPath.printExtractionError(error)
}
}
/// A throwing version of `last`
public var lastComponent: Any? {
get throws { try navigationPath.lastComponent }
}
}
}
extension NavigationPath {
/// Generates an inspectable representation of the current path.
public var inspectable: Inspectable { .init(self) }
}
extension NavigationPath.Inspectable {
public struct Of<Component>: RandomAccessCollection, RangeReplaceableCollection, MutableCollection
where Component: Hashable, Component: Codable {
public var navigationPath: NavigationPath
public init(_ navigationPath: NavigationPath) {
registerTypeForNavigationPathComponent(Component.self)
self.navigationPath = navigationPath
}
public init() {
registerTypeForNavigationPathComponent(Component.self)
self.navigationPath = .init()
}
public var startIndex: Int { navigationPath._startIndex }
public var endIndex: Int { navigationPath._endIndex }
public subscript(position: Int) -> Component {
get {
do {
return try navigationPath.get(at: position) as! Component
} catch {
NavigationPath.printExtractionError(error)
}
}
set {
do {
try navigationPath.set(newValue, at: position)
} catch {
NavigationPath.printExtractionError(error)
}
}
}
public mutating func replaceSubrange<C>(_ subrange: Range<Int>, with newElements: C)
where C : Collection, Component == C.Element {
do {
try navigationPath._replaceSubrange(subrange, with: newElements.map{ $0 as Any })
} catch {
NavigationPath.printExtractionError(error)
}
}
/// A throwing version of `last`
public var lastComponent: Component? {
get throws { try navigationPath.lastComponent as? Component }
}
}
}
extension NavigationPath {
/// Generates a typed inspectable representation of the current path.
public func inspectable<Component>(of type: Component.Type)
-> NavigationPath.Inspectable.Of<Component> {
.init(self)
}
}
// MARK: - Utilities
extension NavigationPath {
public enum Error: Swift.Error {
case nonInspectablePath
case unableToFindMangledName(String)
}
/// This is not super efficient, but at least always in sync.
var lastComponent: Any? {
get throws {
guard !isEmpty else { return nil }
guard let codable else {
throw Error.nonInspectablePath
}
return try JSONDecoder()
.decode(_LastElementDecoder.self, from: JSONEncoder().encode(codable)).value
}
}
static func printExtractionError(_ error: Swift.Error) -> Never {
fatalError("Failed to extract `NavigationPath component: \(error)")
}
/// We use this type to decode the two first encoded components.
private struct _LastElementDecoder: Decodable {
var value: Any
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
let typeName = try container.decode(String.self)
typesRegisterLock.lock()
let mangledTypeName = typeNameToMangled[typeName, default: typeName]
typesRegisterLock.unlock()
guard let type = _typeByName(mangledTypeName) as? (any Decodable.Type)
else {
typesRegisterLock.lock()
defer { typesRegisterLock.unlock() }
if typeNameToMangled[typeName] == nil {
throw Error.unableToFindMangledName(typeName)
}
throw DecodingError.dataCorruptedError(
in: container,
debugDescription: "\(typeName) is not decodable."
)
}
let encodedValue = try container.decode(String.self)
self.value = try JSONDecoder().decode(type, from: Data(encodedValue.utf8))
}
}
}
/// `NavigationPath` codable representation is using `_typeName` instead of mangled names, likely
/// because it is intented to be serialized. But we need mangled names to respawn types using
/// `_typeByName`.
/// I don't know a way to find the mangled name from the type name. If one could generate a list
/// of mangled symbols, we can probably lookup. In the meantime, clients of `Inspectable` should
/// register types they intend to use as path components. This step is realized automatically for
/// `NavigationPath.Inspectable.Of<Component>`, and also automatically when editing the
/// `NavigationPath` using the inspector, but it needs to be performed manually if some
/// `NavigationPath` is deserialized.
///
/// In other words, registering is only required when deserializing an heterogenous
/// `NavigationPath` or an homogenous one with untyped inspection.
/// Register a type for inspection
public func registerTypeForNavigationPathComponent<T>(_ type: T.Type) {
typesRegisterLock.lock()
typeNameToMangled[_typeName(T.self)] = _mangledTypeName(T.self)
typesRegisterLock.unlock()
}
// Register a type for inspection from any value of it
public func registerValueForNavigationPathComponent(_ value: Any) {
let type = type(of: value)
typesRegisterLock.lock()
typeNameToMangled[_typeName(type)] = _mangledTypeName(type)
typesRegisterLock.unlock()
}
private let typesRegisterLock = NSRecursiveLock()
private var typeNameToMangled = [String: String]()
// MARK: - Tests
func runPseudoTests() {
do {
// Check extracting the last component
let path = NavigationPath([0,1,2,3,4,5,6,7,8,9])
assert(path.inspectable.last as? Int == 9)
}
do {
// Check extracting the nth component
let path = NavigationPath([0,1,2,3,4,5,6,7,8,9])
assert(path.inspectable[4] as? Int == 4)
}
do {
// Check setting the nth component
var path = NavigationPath([0,1,2,3,4,5,6,7,8,9]).inspectable
path[4] = -1
let expected = NavigationPath([0,1,2,3,-1,5,6,7,8,9])
assert(path.navigationPath == expected)
}
do {
// Check joining two paths
let path = NavigationPath([0,1,2,3,4,5,6,7,8,9])
let p1 = NavigationPath([0,1,2,3,4])
let p2 = NavigationPath([5,6,7,8,9])
let joinedPath = (p1.inspectable + p2.inspectable).navigationPath
assert(path == joinedPath)
}
do {
// Check editing a path "in the belly".
var inspectable = NavigationPath([0,1,2,3,4,5,6,7,8,9]).inspectable
inspectable.replaceSubrange(3..<6, with: [-1, -2])
let expected = NavigationPath([0,1,2,-1,-2,6,7,8,9])
assert(expected == inspectable.navigationPath)
}
}
extension View {
// Use this method in place of `navigationDestination` to automatically
// register component types.
func inspectableNavigationDestination<D: Hashable, Content: View>(for value: D.Type, destination: @escaping (D) -> Content) -> some View {
registerTypeForNavigationPathComponent(D.self)
return self.navigationDestination(for: value, destination: destination)
}
}
// MARK: -
// Example: Navigation with two destination types and `NavigationPath`
// inpection and manipulation.
struct Destination: Hashable, Codable {
var id: Int
var title: String
}
struct AlternativeDestination: Hashable, Codable {
var id: Int
var title: String
}
struct ContentView: View {
@State var path = NavigationPath().inspectable // A `NavigationPath.Inspectable` value
@State var isModalPresented: Bool = false
var body: some View {
NavigationStack(path: $path.navigationPath) { // We can derive a "mapped" binding from @State
VStack {
Button {
path.append(
Destination(id: 2, title: "Screen #\(2)")
)
} label: {
Label("Navigate to next", systemImage: "arrow.forward")
}
Button {
let destinations = (2...5).map {
Destination(id: $0, title: "Screen #\($0)")
}
path.append(contentsOf: destinations)
} label: {
Label("Navigate to \"5\"", systemImage: "arrow.forward")
}
}
.navigationBarTitleDisplayMode(.inline)
.navigationTitle("NavigationPath inspection")
.inspectableNavigationDestination(for: Destination.self) {
DestinationView(destination: $0, path: $path)
}
.inspectableNavigationDestination(for: AlternativeDestination.self) {
AlternativeDestinationView(destination: $0, path: $path)
}
}
.buttonStyle(.borderedProminent)
.safeAreaInset(edge: .bottom) {
lastComponentOverlay
}
.task {
runPseudoTests()
}
}
var lastComponentOverlay: some View {
// We observe the current last element of the path, extracted from the inspectable path
VStack(spacing: 8) {
Text("Last element of path")
.textCase(.uppercase)
.foregroundStyle(.secondary)
Text(path.last.map(String.init(describing:)) ?? "nil")
.font(.footnote.monospaced()).fontWeight(.semibold)
.frame(maxWidth: .infinity, alignment: .leading)
if !path.isEmpty {
Button {
isModalPresented = true
} label: {
Text("Show NavigationPath")
}
.buttonStyle(.bordered)
}
}
.font(.footnote)
.frame(maxWidth: .infinity)
.padding()
.background(
.ultraThinMaterial.shadow(.drop(radius: 6)),
in: RoundedRectangle(cornerRadius: 11))
.padding(.horizontal)
.animation(.spring(dampingFraction: 0.7), value: (path.last as? Destination)?.id)
.sheet(isPresented: $isModalPresented) {
if path.isEmpty {
VStack {
Text("The path is empty")
Button("Close") { isModalPresented = false }
}
.presentationDetents([.medium])
} else {
NavigationStack {
List {
ForEach(Array(zip(0..., path)), id: \.0) { index, value in
HStack {
Text("\(index)")
Text(String(describing: value))
}
}
.onDelete { offsets in
path.remove(atOffsets: offsets)
}
// This is glitchy in SwifUI Previews
.onMove { source, destination in
path.move(fromOffsets: source, toOffset: destination)
}
}
.safeAreaInset(edge: .bottom) {
if path.count > 1 {
Button {
// Not animating unfortunately, likely by design for deep-linking
withAnimation {
path.shuffle()
}
} label: {
Label("Shuffle", systemImage: "dice")
.frame(maxWidth: .infinity)
.frame(minHeight: 33)
}
.buttonStyle(.borderedProminent)
.padding(.horizontal)
}
}
.environment(\.editMode, .constant(.active))
.navigationTitle("NavigationPath")
.navigationBarTitleDisplayMode(.inline)
}
.presentationDetents([.medium, .large])
}
}
}
}
struct DestinationView: View {
var destination: Destination
@Binding var path: NavigationPath.Inspectable
var body: some View {
let nextDestination = Destination(
id: destination.id + 1,
title: "Screen #\(destination.id + 1)"
)
let nextAlternativeDestination = AlternativeDestination(
id: destination.id + 1,
title: "Alternative Screen #\(destination.id + 1)"
)
List {
NavigationLink("Navigate to \(destination.id + 1)",
value: nextDestination)
NavigationLink("Alternative destination \(destination.id + 1)",
value: nextAlternativeDestination)
}
.safeAreaInset(edge: .top) {
HStack {
Button {
path.append(nextDestination)
} label: {
Label("Navigate to \(destination.id + 1)", systemImage: "arrow.forward")
}
if path.count > 1 {
Button {
withAnimation {
path.shuffle()
}
} label: {
Label("Shuffle", systemImage: "dice")
}
}
}
}
.navigationTitle(destination.title)
}
}
struct AlternativeDestinationView: View {
var destination: AlternativeDestination
@Binding var path: NavigationPath.Inspectable
var body: some View {
let nextDestination = Destination(
id: destination.id + 1,
title: "Screen #\(destination.id + 1)"
)
let nextAlternativeDestination = AlternativeDestination(
id: destination.id + 1,
title: "Alternative Screen #\(destination.id + 1)"
)
List {
NavigationLink("Navigate to \(destination.id + 1)",
value: nextDestination)
NavigationLink("Alternative destination \(destination.id + 1)",
value: nextAlternativeDestination)
}
.scrollContentBackground(Color.yellow)
.safeAreaInset(edge: .top) {
HStack {
Button {
path.append(nextDestination)
} label: {
Label("Navigate to \(destination.id + 1)", systemImage: "arrow.forward")
}
if path.count > 1 {
Button {
withAnimation {
path.shuffle()
}
} label: {
Label("Shuffle", systemImage: "dice")
}
}
}
}
.navigationTitle(destination.title)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
- Useful macOS command line commands
Variously useful CLI commands such as downloading and creating USB installers
- GenerateFake.sourcerytemplate
Sourcery Template for Generating fakes
- What's New in Xcode 14 Previews
Xcode 14 brings a new look to the preview canvas. The pin control is now in the upper left corner and works as before allowing you navigate to different source files while pinning the preview in the canvas. Next to the pin control are the new page controls.
- SwiftUI Renderers and Their Tricks
Unlike most types in SwiftUI, ImageRenderer is not a struct, it is a class. And not just any class, it is an ObservableObject. That means it has a publisher you can subscribe to. All published events by the renderer, mean that the image changed.
- NavigationPath
A type-erased list of data representing the content of a navigation stack. You can manage the state of a NavigationStack by initializing the stack with a binding to a collection of data. The stack stores data items in the collection for each view on the stack. You also can read and write the collection to observe and alter the stack’s state.
When a stack displays views that rely on only one kind of data, you can use a standard collection, like an array, to hold the data. If you need to present different kinds of data in a single stack, use a navigation path instead. The path uses type erasure so you can manage a collection of heterogeneous elements. The path also provides the usual collection controls for adding, counting, and removing data elements.
- Swift language announcements from WWDC22
- Getting UIKit's UICalendarView from iOS 16 fully functioning in a SwiftUI app
The new UICalendarView added to UIKit in iOS 16 looks great but there’s not a SwiftUI equivalent. Here’s how I got a SwiftUI app to show the calendar based on custom dates and update the calendar when dates change.
- Swiftly
Swift references for busy coders
- SwiftUI Renderers and Their Tricks
In the past, if we wanted to convert a SwiftUI view into an image we would wrap the view in a representable, and then use UIKit/AppKit to build our image. With the new renderers that is not longer necessary, but the approach is totally different and there is a whole set of considerations we need to make in order to be successful.
- UIs Are Not Pure Functions of the Model (2018)
The idea of UI being a pure function of the model seems so obviously incorrect, and leads to such a plethora of problems, that it is a bit puzzling how one could come up with it in the first place, and certainly how one would stick with it in face of the avalanche of problems that just keeps coming. A part of this is certainly the current unthinking infatuation with functional programming ideas. These ideas are broadly good, but not nearly as widely or universally applicable as some of their more starry-eyed proponents propose (I hesitate to use the word "think" in this context).
- Functional UI
View models and functional UI look like solutions, and they are indeed effective ways of managing complexity by making all the constituent state visible and enumerated. But in my experience they also encourage a way of programming where you bind as much as possible, and the problem with that is that, as the title of the linked post notes, UIs are not pure functions of the models.
- ExtensionKit
Create executable bundles to extend the functionality of other apps by presenting a user interface. Extensions are executable code bundles, in one app that perform functions in a second, host app. Host apps declare extension points that control the kinds of functionality its extensions can implement. Extensions allow iOS and Mac apps to include code that runs inside system apps. For example, Messages provides extension points so apps can create iMessage Apps. Messages automatically finds extension bundles that target its extension points and makes them available in its app drawer. A Mac app can also declare its own extension points so that other apps can extend the Mac app’s functionality.
- Really structs ought to be implicitly indirected into a COW box after a certain size threshold
- Large structs and stack overflow (code)
Reducing stack costs of structs by using Copy on Write (CoW)
- Large structs and stack overflow (forum)
Short summary:
- Move all stored properties of you struct to a new class called Storage.
- Your struct now only stores an instance of this new class.
- Add computed properties to your struct for each property which gets/sets the value on the class instance.
- Before setting the value in your setter, check if the class instance has a reference count of 1 by using the isKnownUniquelyReferenced.
- If it is not uniquely referenced, you need to copy your storage before setting the value.
- That’s it.
- dotSwift 2019 - Johannes Weiss - High-performance systems in Swift
Languages that have a rather low barrier to entry often struggle when it comes to performance because too much is abstracted from the programmer to make things simple. Therefore in those languages, the key to unlock performance is often to write some of the code in C, collaterally abandoning the safety of the higher-level language.
Swift on the other hand lets you unlock best of both worlds: performance and safety. Naturally not all Swift code is magically fast and just like everything else in programming performance requires constant learning.
Johannes discusses one aspect of what was learned during SwiftNIO development. He debunks one particular performance-related myth that has been in the Swift community ever since, namely that classes are faster to pass to functions than structs.
- Native Debuggers Command Map
Below is a table of equivalent debugger commands for the GDB, LLDB, WinDbg (CDB), and HyperDbg debuggers.
-
My first contribution to Homebrew
- New Formula: GOCR
-
Model View Controller Store: Reinventing MVC for SwiftUI with Boutique
I've built a batteries-included Store that comes with everything you'll need out of the box called Boutique to be the foundation for that data. Boutique does no behind the scenes magic and doesn't resort to shenanigans like runtime hacking to achieve a great developer experience.
-
SwiftUI Changelog
-
A SwiftUI view that displays the phrase someone uses to invoke an App Shortcut.
Use a SiriTipView to display the spoken phrase for the intent you specify. Include an instance of your intent when you create the view, and bind the view to a Boolean to handle the view’s presentation. The following example shows how to configure a button for a reorder intent and bind it to an isInserted variable.
-
WebAuthn — A better alternative for securing our sensitive information online
The Web Authentication API (also known as WebAuthn) is a specification written by the W3C and FIDO, with the participation of Google, Mozilla, Microsoft, Yubico, and others. The API allows servers to register and authenticate users using public key cryptography instead of a password.
-
Mastering NavigationStack in SwiftUI. Navigator Pattern.
SwiftUI is the declarative data-driven framework allowing us to build complex user interfaces by defining the data rendering on the screen. Navigation was the main pain point of the framework from the very first day. Fortunately, things have changed since WWDC 22, and SwiftUI provides the new data-driven Navigation API.
-
WWDC 22 Digital Lounge Archive (SwiftUI + Design)
To help future us (and you!), we’ve copied every question/answer from the lounges of special interest to us: SwiftUI and design. I bet we’ll be referencing them throughout development, and we expect many others to do too. So many valuable insights and tips!
-
Why bother with a random green when you can choose to be a #BADA55!
-
App Clip diagnostics checks App Clip experiences that use physical codes, Safari and iMessage, and it will also check your universal link associated domains configuration. This simple new tool makes it so much easier to get your configuration right.
-
Replace CAPTCHAs with Private Access Tokens
Don't be captured by CAPTCHAs! Private Access Tokens are a powerful alternative that help you identify HTTP requests from legitimate devices and people without compromising their identity or personal information. We'll show you how your app and server can take advantage of this tool to add confidence to your online transactions and preserve privacy.
-
Eliminate data races using Swift Concurrency
Join us as we explore one of the core concepts in Swift concurrency: isolation of tasks and actors. We'll take you through Swift's approach to eliminating data races and its effect on app architecture. We'll also discuss the importance of atomicity in your code, share the nuances of Sendable checking to maintain isolation, and revisit assumptions about ordering work in a concurrent system.
-
Efficiency awaits: Background tasks in SwiftUI
Background Tasks help apps respond to system events and keep time-sensitive data up to date. Learn how you can use the SwiftUI Background Tasks API to handle tasks succinctly. We'll show you how to use Swift Concurrency to handle network responses, background refresh, and more — all while preserving performance and power.
-
Demystify parallelization in Xcode builds
Learn how the Xcode build system extracts maximum parallelism from your builds. We'll explore how you can structure your project to improve build efficiency, take you through the process for resolving relationships between targets' build phases in Xcode, and share how you can take full advantage of available hardware resources when compiling in Swift. We'll also introduce you to Build Timeline — a powerful tool to help you monitor your build efficiency and performance.
-
Debug Swift debugging with LLDB
Learn how you can set up complex Swift projects for debugging. We'll take you on a deep dive into the internals of LLDB and debug info. We'll also share best practices for complex scenarios such as debugging code built on build servers or code from custom build systems.
-
Starting from iOS 16 we can present resizable sheets natively in SwiftUI. In this article we'll look into what we can achieve with the new APIs and what limitations they have in comparison with UIKit.
-
Design protocol interfaces in Swift
Learn how you can use Swift 5.7 to design advanced abstractions using protocols. We'll show you how to use existential types, explore how you can separate implementation from interface with opaque result types, and share the same-type requirements that can help you identify and guarantee relationships between concrete types.
-
navigationDestination(for:destination:)
Associates a destination view with a presented data type for use within a navigation stack.
-
About the security of passkeys
Passkeys are a replacement for passwords. They are faster to sign in with, easier to use, and much more secure.
Passkeys are a replacement for passwords that are designed to provide websites and apps a passwordless sign-in experience that is both more convenient and more secure. Passkeys are a standard-based technology that, unlike passwords, are resistant to phishing, are always strong, and are designed so that there are no shared secrets. They simplify account registration for apps and websites, are easy to use, and work across all of your Apple devices, and even non-Apple devices within physical proximity.
-
Compose custom layouts with SwiftUI
SwiftUI now offers powerful tools to level up your layouts and arrange views for your app's interface. We'll introduce you to the Grid container, which helps you create highly customizable, two-dimensional layouts, and show you how you can use the Layout protocol to build your own containers with completely custom behavior. We'll also explore how you can create seamless animated transitions between your layout types, and share tips and best practices for creating great interfaces.
-
Bringing robust navigation structure to your SwiftUI app
Use navigation links, stacks, destinations, and paths to provide a streamlined experience for all platforms, as well as behaviors such as deep linking and state restoration.
-
A view that displays a root view and enables you to present additional views over the root view.
Use a navigation stack to present a stack of views over a root view. People can add views to the top of the stack by clicking or tapping a NavigationLink, and remove views using built-in, platform-appropriate controls, like a Back button or a swipe gesture. The stack always displays the most recently added view that hasn’t been removed, and doesn’t allow the root view to be removed.
-
Creating Lock Screen Widgets and Watch Complications
Create accessory widgets that appear on the iPhone Lock Screen and as complications on Apple Watch.
Starting with iOS 16 and watchOS 9, WidgetKit allows you to extend the reach of your app to the Lock Screen on iPhone and to the watch face as complications on Apple Watch. They are constantly visible, display your app’s most relevant, glanceable content, and let people quickly access your app for more details.
-
Generics are a fundamental tool for writing abstract code in Swift. Learn how you can identify opportunities for abstraction as your code evolves, evaluate strategies for writing one piece of code with many behaviors, and discover language features in Swift 5.7 that can help you make generic code easier to write and understand.
-
The SwiftUI cookbook for navigation
The recipe for a great app begins with a clear and robust navigation structure. Join the SwiftUI team in our proverbial coding kitchen and learn how you can cook up a great experience for your app. We'll introduce you to SwiftUI's navigation stack and split view features, show you how you can link to specific areas of your app, and explore how you can quickly and easily restore navigational state.
-
Eliminate passwords for your users when they sign in to apps and websites.
Passkeys use iCloud Keychain public key credentials, eliminating the need for passwords. Instead, they rely on biometric identification such as Touch ID and Face ID in iOS, or a specific confirmation in macOS for generating and authenticating accounts.
-
Link fast: Improve build and launch times
Discover how to improve your app's build and runtime linking performance. We'll take you behind the scenes to learn more about linking, your options, and the latest updates that improve the link performance of your app.
-
Improve app size and runtime performance
Learn how we've optimized the Swift and Objective-C runtimes to help you make your app smaller, quicker, and launch faster. Discover how you can get access to efficient protocol checks, smaller message send calls, and optimized ARC simply when you build your app with Xcode 14 and update your deployment target.
-
Meet distributed actors in Swift
Discover distributed actors — an extension of Swift's actor model that simplifies development of distributed systems. We'll explore how distributed actor isolation and location transparency can help you avoid the accidental complexity of networking, serialization, and other transport concerns when working with distributed apps and systems.
-
Demystify parallelization in Xcode builds
Learn how the Xcode build system extracts maximum parallelism from your builds. We'll explore how you can structure your project to improve build efficiency, take you through the process for resolving relationships between targets' build phases in Xcode, and share how you can take full advantage of available hardware resources when compiling in Swift. We'll also introduce you to Build Timeline — a powerful tool to help you monitor your build efficiency and performance.
-
Build device-to-device interactions with Network Framework
Learn how you can create integrated content experiences across multiple devices. We'll introduce you to DeviceDiscoveryUI, which makes it easy to set up communication pathways and connect Apple TV with other devices like iPhone, iPad and Apple Watch. We'll also explore common scenarios and provide best practices to help you enable frictionless device-to-device connectivity.
-
Learn how to take advantage of the power of SwiftUI in your UIKit app. Build custom UICollectionView and UITableView cells seamlessly with SwiftUI using UIHostingConfiguration. We'll also show you how to manage data flow between UIKit and SwiftUI components within your app. To get the most out of this session, we encourage basic familiarity with SwiftUI.
-
Using SwiftUI with UIKit (Sample Code)
Learn how to incorporate SwiftUI views into a UIKit app.
-
Enabling Developer Mode on a device
Grant or deny permission for locally installed apps to run on iOS, iPadOS, and watchOS devices.
-
Send live and on‐demand audio and video to iPhone, iPad, Mac, Apple Watch, Apple TV, and PC with HTTP Live Streaming (HLS) technology from Apple. Using the same protocol that powers the web, HLS lets you deploy content using ordinary web servers and content delivery networks. HLS is designed for reliability and dynamically adapts to network conditions by optimizing playback for the available speed of wired and wireless connections.
-
Using Apple's HTTP Live Streaming (HLS) Tools
Segment your video stream and create media playlists for successful transmission with Apple’s provided tools.
-
Introducing Low-Latency HLS (2019)
Since its introduction in 2009, HTTP Live Streaming (HLS) has enabled the delivery of countless live and on‐demand audio and video streams globally. With the introduction of a new Low-Latency mode, latencies of less than two seconds are now achievable over public networks at scale, while still offering backwards compatibility to existing clients. Learn about how to develop and configure your content delivery systems to take advantage of this new technology.
-
A playground that shows how to use Swift's AttributedString with Markdown
- SwiftUI Property Wrappers
Deciding when to use each of SwiftUI's key property wrappers
- Identity Pinning: How to configure server certificates for your app
If your app sends or receives data over the network, it’s critical to preserve the privacy and integrity of a person’s information and protect it from data breaches and attacks. You should use the Transport Layer Security (TLS) protocol to protect content in transit and authenticate the server receiving the data.
When you connect through TLS, the server provides a certificate or certificate chain to establish its identity. You can further limit the set of server certificates your app trusts by pinning their public-key identities in your app. Here’s how to get started.
- Short Posts and Tips (Swift/iOS)
Swift/iOS tips and tricks
- Detecting SwiftUI preview mode
There may come a time when you need to know whether or not a view is being rendered in a preview or not, or rather if an Xcode process is running for an SwiftUI preview or not.
- SwiftUI: Understanding identity via transitions
In SwiftUI, identity holds the key to understanding how the rendering system works. A View's identity tells SwiftUI which of that View's values correspond to the same rendered view over time. This identity has strong implications for correctness, performance, and as we will see, transitions.
- Faster Xcode builds when switching branches
An approach here is to have multiple copies of your repository. Then you don’t need to worry about stashing any un-comitted work and you can dodge the aforementioned Xcode woes. Alas this also means you need to keep these two copies of the repo up to date. Turns out that git actually supports this out of the box without having to tend to your multiple repo copies manually. The answer is git worktrees🌲.
- macOS Tips & Tricks
Hold down Shift and Option when changing the volume level or brightness to make smaller adjustments.
Hold Control and Shift while mousing over the Dock to temporarily enable magnification.
⌘R replies to the latest message in the conversation. ⇧⌘R replies to the latest thread in the conversation.
- Xcode-Shortcuts
Visual Xcode shortcuts which will help to speed up your development 🚀.
- Copy Images from Storyboards and XIBs
So yesterday I learned something that blew my mind. If you're in Interface Builder and you copy a UI element, you can paste it into an image editor like Photoshop and you get just the UI element with full transparency! 🤯
- The SwiftUI render loop
We will first look into a number of examples of such cases where it is useful to know how the SwiftUI render loop works. Then we will explore the render loop in more detail and ask questions such as: when exactly is the body of a SwiftUI view evaluated. Not "when" as in under what circumstances, but as in: at which point in time? Is a view always drawn on screen immediately after a body is evaluated? How related are body evaluation and screen rendering even? We sometimes use the word "render" for evaluating a body of a view, does that even make sense?
- Creating hex-based colors in UIKit, AppKit and SwiftUI
Although you can use asset catalogs to define colors for your apps and frameworks, there may come a time when you have to create colors from hex codes, for instance when fetching colors from a web api.
You may find it strange that neither UIKit, AppKit nor SwiftUI has initializers for creating colors with hex codes, and you’d be right to think so. Since Apple provides initializers that let you define red, green, blue and alpha values separately, it’s a bit strange.
- How @MainActor works
@MainActor is a Swift annotation to coerce a function to always run on the main thread and to enable the compiler to verify this. How does this work? In this article, I’m going to reimplement @MainActor in a slightly simplified form for illustration purposes, mainly to show how little “magic” there is to it.
- Swift Code Injection using dyld_dynamic_interpose
To inject code into an application the first step is to recompile the file being injected.The correct command for this is extracted the Xcode “.xcactivitylog” files and theresulting object file is linked to a dynamic library that is loaded into the application.
- Trickery to Tame Big WebAssembly Binaries
What can we do? In this post I go over some techniques I've been playing with. They're largely hacks, so please only read for enjoyment and not edification. :)
- Weak Self — Closure Rules of Thumb
- Only use a strong self for non-@escaping closures (ideally, omit it & trust the compiler)
- Use weak self if you’re not sure
- Upgrade self to a strongly-retained self at the top of your closure.
- How much does more memory benefit Xcode?
Xcode alone can fill the RAM on a 16GB system. Yeah, okay, half of that is "Cached Files" (not app memory) so the effect is subtle. Incremental builds are 5% slower compared to a 32GB system but clean builds are about the same.
- Model View Controller for SwiftUI
Overall SwiftUI has been well received after its introduction. However, something most developers stumble upon quickly is how to structure non-trivial applications. One option is to just stick to MVC and get a reasonably clean architecture that isn’t full of hacks.
- Using new Swift Async Algorithms package to close the gap on Combine
As developers have started adopting the new Swift Concurrency functionality introduced in Swift 5.5, a key area of interest has been around how this works with the Combine framework and how much of existing Combine based functionality can be replaced with async/await, AsyncSequence etc based code. In particular there has been some discussion around how Combine Publishers can be replaced by AsyncSequence and, in that context, one noted gap in initial offerering was difference in the range of operators available for both approaches. There have been attempts already to close that gap using, for example, projects like AsyncExtensions but, with the announcment recently of Swift Async Algorithms package, we will now have a more standard approach to supporting some of those missing operators. In this article I’m going to outline an example of how existing Combine Publisher based code can be replaced with code based on use of AsyncSequence and Swift Async Algorithms.
- Concurrent/Async barrier
Periodic reminder that you probably don’t want the “concurrent” flag on dispatch queues in general, but you especially don’t want the popular “barrier async set, sync get” atomic property antipattern. It’s like using a 747 to go to the house next door.
- Understanding SwiftUI Layout Behaviors
The SwiftUI layout system is more predictable and easier to understand than UIKit layout system. But this does not mean how it works is entirely straightforward.
For newcomers with no preconception of how layout historically worked on Apple platforms, official documentation about the SwiftUI layout system might namely be incomplete or obscure. The number of views and modifiers, as well as their various behaviors, can be quite overwhelming. Even for seasoned UIKit developers it can be difficult to figure out how SwiftUI layout system works, as its core principles are quite different from UIKit well-known concepts of Auto Layout constraints, springs and struts.
This article explores the essential rules and behaviors of the SwiftUI layout system and explains how you should reason about it. It also introduces a formalism that helps characterize views and their sizing behaviors in general. It finally provides a list of the sizing behaviors for most SwiftUI built-in views.
- Dismissing SwiftUI Views
SwiftUI has a less clumsy mechanism for dismissing presented views in iOS 15.
- SwiftUI performance tips
Optimizing performance is definitely one of the most interesting topics, not only on iOS, but software development in general. There are many thought provoking challenges, accompanied with a detective work to find the places that stand between your product and the optimal and performant user experience.
For debugging SwiftUI performance issues, I usually use the following profiling templates:
- Animation hitches — for detecting the hitches.
- SwiftUI — for counting how many times the view has been redrawn.
- Time Profiler — for checking which methods took the most time to execute.
- Replicating Types in Swift
CRDTs, which I will simply call ‘replicating types’ from here on, are data types that have the ability to merge themselves when changes are made on different devices, in order to reach a consistent state. They have built-in logic which allows them to be updated independently, and then merged back together in a completely deterministic way, such that all syncing devices end up with the same value.
- Xcode Cloud
Xcode Cloud is a continuous integration and delivery service built into Xcode and designed expressly for Apple developers. It accelerates the development and delivery of high-quality apps by bringing together cloud-based tools that help you build apps, run automated tests in parallel, deliver apps to testers, and view and manage user feedback.
- Lifetime of State Properties in SwiftUI
One of the challenging parts of SwiftUI is really understanding the way it manages view state (for example, through @State and @StateObject). In theory, it's pretty simple: anytime you want associated view state you just create a property with @State and you're done.
- TBCTestStore (TCA)
Universal test store interface that can be used in both Exhaustive and non-Exhaustive mode
- Xcode Build System:
defaults write com.apple.dt.XCBuild EnableSwiftBuildSystemIntegration 1
The build system and Swift compiler have a new mode that better utilizes available cores, resulting in faster builds for Swift projects. The mode is opt-in, and you can enable it globally.
- Swift Packages:
defaults write com.apple.dt.Xcode XPMAvoidUpdatingUnchangedPackages No
Making changes to one or more packages in a workspace and then starting a build may cause Xcode to crash.
- xcdebug
- Development & design tools for iOS developers
These are the 33 tools I use daily and have saved me so much time that I can't recommend them enough.
- WTF Auto Layout
Demystify Auto Layout constraint error logs
- NSDateFormatter
Easy Skeezy Date Formatting for Swift and Objective-C
- Quick Type
Convert JSON to Swift code
- Screen Sizes
A complete guide for Apple displays
- Cubic Bezier
Play around with bezier path
- Regex101
Build, test, and debug regex Regular expression tester with syntax highlighting, explanation, cheat sheet for PHP/PCRE, Python, GO, JavaScript, Java, C#/.NET.
- Happy Hues
Not sure what colors to use in your designs or where to use them? Happy Hues is a color palette inspiration site that acts as a real world example as to how the colors could be used in your design projects.
- Mobbin
Design screenshots collection
- Paywall
Curation of paywall screens
- Checklist Design
A collection of the best design practices.
- Give your iOS Simulator superpowers
Give your iOS Simulator superpowers
- FengNiao
A command line tool for cleaning unused resources in Xcode.
- Build Time Analyzer for Xcode
Build Time Analyzer for Swift
- DevCleaner
If you want to reclaim tens of gigabytes of your storage used for various Xcode caches - this tool is for you!
- replaces the time the build finished with how long the build took
defaults write http://com.apple.dt.Xcode ShowBuildOperationDuration YES
- How to debug allocation regressions
Usually, your journey will start by detecting that an allocation test regressed. So let's first start by looking at how to run the allocation counter tests.
- PlaygroundTester
PlaygroundTester enables you to easily run tests for your iPad Playgrounds 4 project.
- Better performance with canvas in SwiftUI
It is said that use of Canvas to create complex shapes can provide better performance in SwiftUI. This article compares performance of scrolling through multiple instances of the same card pattern created using shape, canvas or image.
- Building a Custom Combine Operator for Exponential Backoff
In this post, you will learn about Combine operators: what they are, how they work, and how refactoring our code into a custom Combine operator will make it easier to reason about and more reusable at the same time.
- Native Network Monitoring In Swift
We'll take a look at a native solution for monitoring network connectivity on iOS with Swift 5 and how to use the Network Link Conditioner.
- What is Developer Experience? a roundup of links and goodness
Developer Experience is about creating an environment in which a developer can do their best work. DX is the context in which developer productivity can be unleashed, in which individual needs can be successfully balanced with those of the engineering team. DX is about developer feelings – it is a sociotechnical system which should consider every touchpoint a developer interacts with to plan and produce software, from learning a platform to the very first line of code all the way through its promotion into production. From documentation to SDKs to version control to monitoring and observability, everything a developer touches will have an impact on their productivity. Culture too, helps to define a good DX of the lack of it.
- Embedding a dylib in a Swift Package
- Xcode Tips
Collections of tips for Xcode.
- UIKit Catalog: Creating and Customizing Views and Controls
Customize your app’s user interface with views and controls.
- VirtualFileSystem.swift
allows to load a package from a serialized form
- customPackageContainerProvider
a custom package container provider
- Debugging SwiftUI views: what caused that change?
Debugging SwiftUI views is an essential skill to own when writing dynamic views with several redrawing triggers. Property wrappers like @State and @ObservedObject will redraw your view based on a changed value. In many cases, this is expected behavior, and things look like they should. However, in so-called Massive SwiftUI Views (MSV), there could be many different triggers causing your views to redraw unexpectedly.
- Fixing SwiftUI's Automatic Preview Updating Paused
If you work with SwiftUI, or have even just tried SwiftUI previews, then you’ve seen this annoying message: Automatic preview updating paused. To some devs it happens all the time and is extremely frustrating. In this article I’ll explain why this happens and how it can be solved. Let’s dig in!
- Profiling binary size on iOS using Bloaty
I’ve been using this tool called Bloaty McBloatface1 to attribute the contribution of each swift module or file to our app’s binary. And it has worked out really well for me, the CLI tool is super fast, gives lots of information, supports diffing and has so many options that configurations and options that it’s difficult to explore it all in a single blog post.
- Apple Swift Lexicon
This file defines several terms used by the Swift compiler and standard library source code, tests, and commit messages.
- Microapps architecture in Swift. Resources and localization.
In this post, we will talk about sharing resources between modules and separating the localization of feature modules. Swift Packages support localization out of the box. We added the defaultLocalization parameter to the package declaration in the example above. This parameter is necessary if you want to support localization. Now you can create en.lproj, es.lproj, or any-locale-identifier.lproj folders in your module to place your Localizable.strings files with particular translations. Remember that you still need to specify the correct bundle whenever you want to access the localization of the current module.
- A type can be Sendable if any of these three conditions is true
- It has no mutable state
- It has mutable state, but
=
creates a copy of that state that doesn't share anything with the original - It has mutable atate and
=
doesn't prevent sharing, but you are synchronizing access somehow (e.g. @MainActor, COW, atomics, private queues, locks)
As a rule of thumb, most structs/enums can be Sendable as long as all of their stored properties have Sendable types; if you try to conform a struct and that isn’t the case, you’ll get an error unless you use @unchecked.
- Tips on Resetting the Bluetooth Module
Resetting the Bluetooth Module in that method is simply just no longer an option. It is just not part of macOS Monterey. For reference, I wrote this user tip back in April 2021, prior to the release of macOS Monterey: Use "Reset the Bluetooth module" to Fix Constant Bluetooth Disconnections
- Restart the Mac
- Reset the SMC and your NVRAM:
- Use this Terminal Command:
sudo pkill bluetoothd
- How to reset the SMC of your Mac
Resetting the system management controller (SMC) can resolve certain issues related to power, battery, fans, and other features.
- Reset NVRAM or PRAM on your Mac
NVRAM (nonvolatile random-access memory) is a small amount of memory that your Mac uses to store certain settings and access them quickly. PRAM (Parameter RAM) stores similar information, and the steps for resetting NVRAM and PRAM are the same. Settings that can be stored in NVRAM include sound volume, display resolution, startup-disk selection, time zone, and recent kernel panic information. The settings stored in NVRAM depend on your Mac and the devices that you're using with your Mac. If you experience issues related to these settings or others, resetting NVRAM might help. For example, if your Mac starts up from a disk other than the one selected in Startup Disk preferences, or a question mark icon briefly appears before your Mac starts up, you might need to reset NVRAM. How to reset NVRAM: Option keyplusCommand keyplusP keyplusR key
- An early look at Swift extensible build tools
A plugin is the way that the extensible build tools feature provides us to define what commands we want to run alongside, before or after (not available yet) our builds.
- Unlisted app distribution
Release your apps that aren’t suited for public distribution as unlisted on the App Store, discoverable only with a direct link. Unlisted apps don’t appear in any App Store categories, recommendations, charts, search results, or other listings. They can also be accessed through Apple Business Manager and Apple School Manager. Apps for specific organizations, special events, or research studies, or apps used as employee resources or sales tools are good candidates for unlisted distribution.
- BackLog for Mac
Easily load specific log-messages from your Mac’s archives, or send backlog://-links to others and make retrieving diagnostic info super-easy.
- The structure of a Swift Package
Explore packages in more detail
- MacOS screenshotting tips
⇧⌘4, then space, then hold ⌘ to screenshot individual panels and floating windows.
- Cascading Environment actions in SwiftUI
By defining a cascading action type, and a helper modifier to handle the chain building, we have essentially introduced a variant of the observer pattern in SwiftUI.
- Forcing an app out of memory on iOS
Being able to simulate situations where your app goes out of memory is incredibly useful when you’re working on features that rely on your app being resumed in the background even when it’s out of memory. Background uploads and downloads are just some examples of when this trick is useful.
- A Swift Recoverable Precondition That Can Throw
Checks a necessary condition for making forward progress.
- Loading Media Data Asynchronously
Simplify asynchronous property loading using language-level concurrency features.
- App Startup Time: Past, Present, and Future (2017)
Learn about the dyld dynamic linker used on Apple platforms, how it's changed over the years, and where it's headed next. Find out how improved tooling makes it easier to optimize your app's launch time, and see how new changes coming in dyld will bring even further launch time improvements.
- Optimizing App Startup Time (2016, Youtube bootleg)
- Method dispatch in Swift (2017)
Method dispatch is a term referring to mechanisms by which the program determines which operation should be executed (by operation, I mean a set of instructions). There are times we expect a method behavior to be determined only at runtime. This motivation give rise to different mechanisms of dispatching a method, each of which has its own pros and cons.
- Meet AsyncSequence (2021)
Iterating over a sequence of values over time is now as easy as writing a “for” loop. Find out how the new AsyncSequence protocol enables a natural, simple syntax for iterating over anything from notifications to bytes being streamed from a server. We'll also show you how to adapt existing code to provide asynchronous sequences of your own.
- Understanding Swift Performance (2016)
Find out how structs, classes, protocols, and generics are implemented in Swift. Learn about their relative costs in different dimensions of performance. See how to apply this information to speed up your code.
- Web API Client in Swift
The goal is to use the minimum number of abstractions and make the code easy to understand and extend. I’m going with Apple technologies exclusively for this project: URLSession, Codable, Async/Await, and Actors.
- Pulse: Structured Logging System
Pulse is a powerful logging system. Record and inspect network requests and logs right from your iOS app using Pulse Console. Share and view logs in Pulse macOS app. Logs are recorded locally and never leave your device.
- Sourcery Pro
Sourcery Pro is a Mac App that extends Xcode with the ability to create your own live templates that understand your code structure. Do you hate writing same repetitive Swift patterns over and over again? Now you don’t need to, it’s just a shortcut away.
- https://github.com/twostraws/Sitrep
a source code analyzer for Swift projects, giving you a high-level overview of your code
- Debug Overrides
This is a copy of debug overrides available through Xcode UI that boils down to calling certain private APIs.
- Applying Matte Effects to People in Images and Video
Generate image masks for people automatically by using semantic person-segmentation.
- Connecting to a Service with Passkeys
Allow users to sign in to a service without typing a password.
- How To Solve Any iOS Crash Ever
The ability to debug complex crashes is not something immediate. Keep this out of your expectations: there's no magical instrument that you forgot to run that will give you the output you're expecting. When it comes to complex crashes, what we need to do instead is prepare our environment so that these issues are better understood when they arrive, making them more actionable. Let's see how to do that!
- 30 tips to make you a better iOS developer
I’ve compiled a list of dev tips that I feel every iOS developer should know. Ready? Here we go!
- Doing Advanced Optimization to Further Reduce Your App’s Size
Optimize your app’s asset files, adopt on-demand resources, and reduce the size of app updates.
- Doing Basic Optimization to Reduce Your App’s Size
Adjust your project’s build settings, and use technologies like bitcode and asset catalogs early in your app’s development life cycle.
- Choosing Between Structures and Classes
Decide how to store data and model behavior.
- Reducing Your App’s Size
Measure your app’s size, optimize its assets and settings, and adopt technologies that help streamline installation over a mobile internet connection.
- Everything You Never Wanted To Know About Linker Script
Everything in this post can be found in excruciating detail in GNU ld’s documentation; lld accepts basically the same syntax. There’s no spec, just what your linker happens to accept.
- What does a linker do?
It’s simple: a linker converts object files into executables and shared libraries. Let’s look at what that means.
- Prepare Your App for Prewarming
In iOS 15 and later, the system may, depending on device conditions, prewarm your app — launch nonrunning application processes to reduce the amount of time the user waits before the app is usable.
- Making Dependencies Available to Xcode Cloud
Review dependencies and make them available to Xcode Cloud before you configure your project to use Xcode Cloud.
- ITSAppUsesNonExemptEncryption
A Boolean value indicating whether the app uses encryption.
- Deal with nested SPM errors
- Convert a Universal (FAT) Framework to an XCFramework
Separate the simulator and device architectures into separate binaries such that the size of each sliced up binary is less than the whole. This is easy to do using the new-ish XCFramework packaging.
- Improving Your App's Performance
Model, measure, and boost the performance of your app by using a continuous-improvement cycle.
- The Apple Compact Unwinding Format: Documented and Explained
So you have a running program. Functions call other functions, so you need a mechanism to save the caller’s state while the callee runs, and then restore that state when the callee completes. Some of this is defined by ABIs, but even with a defined ABI there’s a lot of wiggle room for the callee to mess around.
- Protecting the User’s Privacy
Designing for user privacy is important. Most Apple devices contain personal data that the user doesn’t want to expose to apps or to external entities. If your app accesses or uses data inappropriately, the user might stop using your app and even delete it from their device. Access user or device data only with the user’s informed consent obtained in accordance with applicable law. In addition, take appropriate steps to protect user and device data, and be transparent about how you use it.
- Machine Learning Research at Apple
- Underscored Attributes Reference
The Swift reference has a chapter discussing stable attributes. This document is intended to serve as a counterpart describing underscored attributes, whose semantics are subject to change and most likely need to go through the Swift evolution process before being stabilized.
- What is garbage collection? — Chris Lattner (2016)
Technically speaking, reference counting is a form of garbage collection, but I get what you mean. Since there are multiple forms of GC, I'll assume that you mean a generational mark and sweep algorithm like you’d see in a Java implementation.
- Swift Performance — Joe Groff (2020)
It's worth remembering Swift's implementation of ARC is still far from optimal. Swift 5.3's optimizer significantly reduces the number of ARC calls in optimized code; we've seen up to 2x improvements in hot parts of SwiftUI and Combine without code changes. There will continue to be ARC optimizer improvements as we propagate OSSA SIL through the optimizer pipeline as well. (However, the main benefit of ARC over other forms of GC will always be lower-overhead interop with non-GC-managed resources, such as the large volumes of C, C++, and growing amount of value-oriented Swift code that implements the lower level parts of the OS, rather than the performance of the heap management itself.)
- Optimizing ProMotion Refresh Rates for iPhone 13 Pro and iPad Pro
Provide custom animated content for ProMotion displays.
- LLVM Internals: the bitcode format
LLVM provides both a textual form that looks roughly like a C-family programming language, and a binary form (bitcode, in LLVM’s parlance) that’s denser and (ostensibly) faster to parse. The two forms are semantically identical, and trivial to produce and convert between.
- Deleting your app from the iOS simulator during UI tests
resetting your app between UI tests by completely deleting it
- Bypassing objc_msgSend (2019)
The advantage we have over
objc_msgSend
is that as humans (or as a compiler), we have static type information and an understanding of the surrounding code which lets us guess, statically and with high accuracy, what the target is. In fact, we can just speculate that the call will go to the predicted method, and, taking a leaf out ofobjc_msgSend
’s book, wrap a direct call to it in the barest minimum of checking to make sure that we were correct in our prediction.
- What's .self, .Type and .Protocol? Understanding Swift Metatypes (2018)
You can define the metatype of any type, including classes, structs, enums and protocols as being the name of that type followed by .Type.
- Swift metadata (2019
The Swift runtime keeps a metadata record for every type used in a program, including every instantiation of generic types. These metadata records can be used by (TODO: reflection and) debugger tools to discover information about types.
- Faster Swift and Clang Builds
This is a collection of suggestions that reduce the time it takes to build the Swift and Clang compilers.
- SwiftCodeSan
SwiftCodeSan is a tool that "sanitizes" code written in Swift.
- Understanding how and when SwiftUI decides to redraw views
There's a good chance that you're using SwiftUI and that you're not quite sure how and when SwiftUI determines which views should redraw. There's an equal likelihood that your setup isn't as performant as you might think but you're just not seeing any issues yet.
- Every SwiftUI Environment Value explained
SwiftUI's Environment is one of the most important pillars of Apple's declarative UI framework. There are many aspects of this infrastructure: in this article, let's review all environment values that SwiftUI offers.
- SwiftUI Secrets
View._printChanges()
This static function was added in iOS 15 and is perhaps the most widely known one, seeing as Apple folk are encouraging people to use it. You can use it print out to Xcode debug console what triggered SwiftUI to evaluate thebody
function of your view. - Abstracting Navigation in SwiftUI
- A sneak peek into SwiftUI's graph
- AppKit is Done
- The Strategic SwiftUI Data Flow Guide (+ Infographic)
- Call
Self._printChanges()
inside the body of a view to print out the changes that have triggered the view update.
- SwiftLint for Swift Packages
This article explains how to use a post action script in Xcode to automatically trigger SwiftLint afer a successful Swift Package compilation.
- Distributing closed-source frameworks with SPM
How to distribute closed-source XCFrameworks-based products with the Swift Package Manager.
- Bundling Resources with a Swift Package
Add resource files to your Swift package and access them in your code.
- fireAndCatch - For ignoring Output, while catching Failures
Turns any publisher into an
Effect
for any output and failure type by ignoring all output, but retaining any failure.
- IPATool
Command-line tool that allows searching and downloading app packages (known as ipa files) from the iOS App Store
- ARC in Swift: Basics and beyond
Learn about the basics of object lifetimes and ARC in Swift. Dive deep into what language features make object lifetimes observable, consequences of relying on observed object lifetimes and some safe techniques to fix them.
- Analyze HTTP traffic in Instruments
Learn to use the Instruments Network template to record and analyze your app's HTTP traffic. We'll show you how to explore and visualize the behavior of sessions, tasks, and individual HTTP requests to ensure data is transmitted efficiently and respects people's privacy.
- Demystify SwiftUI
Peek behind the curtain into the core tenets of SwiftUI philosophy: Identity, Lifetime, and Dependencies. Find out about common patterns, learn the principles that drive the framework, and discover how you can use them to guarantee correctness and performance for your app.
- Detect and diagnose memory issues
Discover how you can understand and diagnose memory performance problems with Xcode. We'll take you through the latest updates to Xcode's tools, explore Metrics, check out the memgraph collection feature in XCTest, and learn how to catch regressions using a Performance XCTest.
- Detect bugs early with the static analyzer
Discover how Xcode can automatically track down infinite loops, unused code, and other issues before you even run your app. Learn how, with a single click, Xcode can analyze your project to discover security issues, logical bugs, and other hard-to-spot errors in Objective-C, C, and C++. We'll show you how to use the static analyzer to save you time investigating bug reports and improve your app's overall quality.
- Discover breakpoint improvements
Breakpoints can help you debug issues by allowing you to pause and inspect problems in the middle of a process. Discover the latest improvements to breakpoints in Xcode including column and unresolved breakpoints. We'll also go over best practices for general breakpoints and LLDB tips and tricks.
- Distribute apps in Xcode with cloud signing
Discover how to distribute your apps directly to App Store Connect and all the distribution methods supported in Xcode. Explore how to automate distribution for your apps, and learn about improvements to the distribution workflow like cloud signing, app record creation, and build number management.
- Explore advanced project configuration in Xcode
Working with more complex Xcode projects? You've come to the right place. Discover how you can configure your project to build for multiple Apple platforms, filter content per-platform, create custom build rules and file dependencies, and more. We'll take you through multi-platform framework targets, detail how to optimize your project and scheme configuration, and show you how to make effective use of configuration settings files. We'll explore configuring schemes for parallel builds and implicit dependencies, script phases, custom build rules, setting up input and output file dependencies, build phase file lists, and deduplicating work via aggregate targets. Lastly, find out more about the build settings editor, how levels work, and configuration settings file syntax.
- Explore structured concurrency in Swift
When you have code that needs to run at the same time as other code, it's important to choose the right tool for the job. We'll take you through the different kinds of concurrent tasks you can create in Swift, show you how to create groups of tasks, and find out how to cancel tasks in progress. We'll also provide guidance on when you may want to use unstructured tasks.”
- Get ready for iCloud Private Relay
iCloud Private Relay is an iCloud+ service that prevents networks and servers from monitoring a person's activity across the internet. Discover how your app can participate in this transition to a more secure and private internet: We'll show you how to prepare your apps, servers, and networks to work with iCloud Private Relay.
- iOS Memory Deep Dive (2018)
Discover how memory graphs can be used to get a close up look at what is contributing to an app's memory footprint. Understand the true memory cost of an image. Learn some tips and tricks for reducing the memory footprint of an app.
- Symbolication: Beyond the basics
Discover how you can achieve maximum performance and insightful debugging with your app. Symbolication is at the center of tools such as Instruments and LLDB to help bridge the layers between your application's runtime and your source code. Learn how this process works and the steps you can take to gain the most insight into your app.
- Write a DSL in Swift using result builders
Some problems are easier to solve by creating a customized programming language, or “domain-specific language.” While creating a DSL traditionally requires writing your own compiler, you can instead use result builders with Swift 5.4 to make your code both easier to read and maintain. We'll take you through best practices for designing a custom language for Swift: Learn about result builders and trailing closure arguments, explore modifier-style methods and why they work well, and discover how you can extend Swift's normal language rules to turn Swift into a DSL. To get the most out of this session, it's helpful (though not necessary) to have some experience writing SwiftUI views. You won't need to know anything about parser or compiler implementation.
- How-to: Create compile time reminders in Xcode
How-to: Create compile time reminders in Xcode
- Minimum requirements and supported SDKs
- Convincing Xcode to Map Vim Keys
I've tried to make it clear in the title, but hopefully you haven't gotten to this page thinking that Apple provides a built-in way to add custom key mappings in Xcode 13's new Vim Mode. Unfortunately, this functionality just isn't easily configurable. Instead, this is one of those “but everything's a little configurable with enough swizzling & pointer arithmetic” kind of posts.
- Connecting Xcode To A Running Process (2018)
Did you know you can connect the Xcode debugger to a running process? You can also have Xcode wait for a process to launch before connecting. This helps when debugging issues when your App is launched in response to an external event such as a notification. We can also use it to peek at some of the built-in Apps in the simulator.
- Xcode Keyboard Shortcuts
Here’s my cheat sheet of the ones I find useful enough to learn. This is not a comprehensive list of every Xcode shortcut.
- Configuration Settings File (xcconfig) format
- Complete reference of every build setting supported for the latest version of Xcode
- Conditional Compilation, Part 1: Precise Feature Flags
- Conditional Compilation, Part 2: Including and Excluding Source Files
- Conditional Compilation, Part 3: App Extensions