# 2023 ## December * [MetalFX](https://developer.apple.com/documentation/metalfx) > _Boost your Metal app’s performance by upscaling lower-resolution content to save GPU time._ > > The `MetalFX` framework integrates with [Metal](https://developer.apple.com/documentation/metal) to upscale a relatively low-resolution image to a higher output resolution in less time than it takes to render directly to the output resolution. > > Use the GPU time savings to further enhance your app or game’s experience. For example, add more effects or scene details. > > `MetalFX` gives you two different ways to upscale your input renderings: > > * Temporal antialiased upscaling > * Spatial upscaling > > If you can provide pixel color, depth, and motion information, add an [MTLFXTemporalScaler](https://developer.apple.com/documentation/metalfx/mtlfxtemporalscaler) instance to your render pipeline. Otherwise, add an [MTLFXSpatialScaler](https://developer.apple.com/documentation/metalfx/mtlfxspatialscaler) instance, which only requires a pixel color input texture. > > Because the scaling effects take time to initialize, make an instance of either effect at launch or when a display changes resolutions. Once you’ve created an effect instance, you can use it repeatedly, typically once per frame. * [The MPSKernel Class](https://developer.apple.com/documentation/metalperformanceshaders/the_mpskernel_class) > The [MPSKernel](https://developer.apple.com/documentation/metalperformanceshaders/mpskernel) is the base class for all Metal Performance Shaders kernels. It defines the baseline behavior for all kernels, declaring the device to run the kernel on, some debugging options, and a user-friendly label, should one be required. Derived from this class are the [MPSUnaryImageKernel](https://developer.apple.com/documentation/metalperformanceshaders/mpsunaryimagekernel) and [MPSBinaryImageKernel](https://developer.apple.com/documentation/metalperformanceshaders/mpsbinaryimagekernel) subclasses, which define shared behavior for most image processing kernels (filters) such as edging modes, clipping, and tiling support for image operations that consume one or two source textures. Neither these nor the [MPSKernel](https://developer.apple.com/documentation/metalperformanceshaders/mpskernel) class are meant to be used directly. They just provide API abstraction and in some cases may allow some level of polymorphic manipulation of image kernel objects. * [threadDictionary](https://developer.apple.com/documentation/foundation/thread/1411433-threaddictionary) > _The thread object's dictionary._ > You can use the returned dictionary to store thread-specific data. The thread dictionary is not used during any manipulations of the `NSThread` object—it is simply a place where you can store any interesting data. For example, Foundation uses it to store the thread’s default `NSConnection` and `NSAssertionHandler` instances. You may define your own keys for the dictionary. * [**list of notable initial algebras and terminal coalgebras**](https://ncatlab.org/nlab/show/list+of+notable+initial+algebras+and+terminal+coalgebras) * [VideoPlaybackController](https://developer.apple.com/documentation/realitykit/videoplaybackcontroller) > _An object that controls the playback of video for a video material._ * [Observe audio session notifications to ensure that your app responds appropriately to interruptions.](https://developer.apple.com/documentation/avfaudio/handling_audio_interruptions) > _Observe audio session notifications to ensure that your app responds appropriately to interruptions._ > > Interruptions are a common part of the iOS and watchOS user experiences. For example, consider the scenario of receiving a phone call while you’re watching a movie in the TV app on your iPhone. In this case, the movie’s audio fades out, playback pauses, and the sound of the call’s ringtone fades in. If you decline the call, control returns to the TV app, and playback begins again as the movie’s audio fades in. At the center of this behavior is your app’s audio session. As interruptions begin and end, the audio session notifies any registered observers so they can take appropriate action. For example, [AVPlayer](https://developer.apple.com/documentation/avfoundation/avplayer) monitors your app’s audio session and automatically pauses playback in response to interruption events. You can monitor these changes by key-value observing the player’s [timeControlStatus](https://developer.apple.com/documentation/avfoundation/avplayer/1643485-timecontrolstatus) property, and update your user interface as necessary when the player pauses and resumes playback. * [Presenting SharePlay activities from your app’s UI](https://developer.apple.com/documentation/groupactivities/promoting-shareplay-activities-from-your-apps-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](https://developer.apple.com/design/Human-Interface-Guidelines/shareplay). * [Applying Realistic Material and Lighting Effects to Entities](https://developer.apple.com/documentation/realitykit/applying-realistic-material-and-lighting-effects-to-entities) > _Enhance the appearance of objects in a RealityKit scene with Physically Based Rendering (PBR)._ > > A [Material](https://developer.apple.com/documentation/realitykit/material) instance describes the surface properties of an entity and controls how RealityKit renders that entity. A [PhysicallyBasedMaterial](https://developer.apple.com/documentation/realitykit/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](https://developer.apple.com/documentation/realitykit/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](https://developer.apple.com/documentation/realitykit/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](https://spline.design/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](https://developer.apple.com/documentation/groupactivities/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](https://developer.apple.com/documentation/groupactivities/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](https://developer.apple.com/documentation/groupactivities/defining-your-apps-shareplay-activities). * [Supporting Coordinated Media Playback](https://developer.apple.com/documentation/avfoundation/media_playback/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](https://developer.apple.com/documentation/avfoundation/avplayerplaybackcoordinator), that synchronizes the timing of [AVPlayer](https://developer.apple.com/documentation/avfoundation/avplayer) objects across devices. Apps use the GroupActivities framework to connect playback coordinators using a [GroupSession](https://developer.apple.com/documentation/groupactivities/groupsession) object. * [Symbolicating SwiftUI (and any Apple Framework), Part 2](https://www.emergetools.com/blog/posts/symbolicating-swiftui-and-any-apple-framework-part-2#understanding-crash-reports) > 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](https://github.com/blacktop/ipsw) 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 > ``` > * [sg.nvim](https://github.com/sourcegraph/sg.nvim) > The official Sourcegraph/Cody plugin for Neovim * [Trigger property observers from initializers in Swift](https://nilcoalescing.com/blog/TriggerPropertyObserversFromInitializersInSwift) > In Swift, property observers such as `willSet` and `didSet` 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](https://useyourloaf.com/blog/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: > > 1. 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. > 1. 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. > 1. 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. > 1. 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. > 1. 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. > 1. 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](https://www.emergetools.com/symbolicate) > 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](https://github.com/EmergeTools/ETSymbolication/?tab=readme-ov-file#supported-symbols). > > 📚 Read our posts exploring how we uncovered [hidden symbols](https://www.emergetools.com/blog/posts/symbolicating-swiftui-and-any-apple-framework) + [built an open-source symbolication reference](https://www.emergetools.com/blog/posts/symbolicating-swiftui-and-any-apple-framework-part-2). > > 🍎 Check out the open source repo to [learn how to contribute](https://github.com/EmergeTools/ETSymbolication/?tab=readme-ov-file#contributing) more symbols to this tool * [Proceedings of the Sixth International Conference on Applied Category Theory 2023](https://cgi.cse.unsw.edu.au/~eptcs/content.cgi?ACT2023#EPTCS397.0) > 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](https://github.com/keith/dyld-shared-cache-extractor) > _A CLI for extracting libraries from Apple's dyld shared cache file_ > > [As of macOS Big Sur](https://mjtsai.com/blog/2020/06/26/reverse-engineering-macos-11-0), 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](https://developer.apple.com/tutorials/swiftui-concepts/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](https://www.unison.cloud/docs/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](https://discord.gg/rFpgdWmcMs) 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](https://unison.cloud) is monitored by the [Unison Cloud team](https://www.unison.cloud/docs/onboarding/#theteam) and is another place you can get help. > * For general Unison language questions and announcements, visit the [Unison Slack](https://unison-lang.org/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! > * [Your Smart TV Knows What You’re Watching](https://themarkup.org/privacy/2023/12/12/your-smart-tv-knows-what-youre-watching) > Here’s how to turn off “automated content recognition,” the Shazam-like software on smart TVs that tracks what you’re watching. * [GlobalActor](https://developer.apple.com/documentation/swift/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](https://rockyshikoku.medium.com/the-reference-book-of-realitykit-cf9babb86dd) > 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.](https://www.meticulous.ai) > Cover the **1000s of edge cases** of your application - in 5 minutes of setup, with **zero** maintenance. * [GitHub Markdown Alerts](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#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. > > ```markdown > > [!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](https://github.com/ikatyang/emoji-cheat-sheet/blob/master/README.md) > This cheat sheet is automatically generated from [GitHub Emoji API](https://api.github.com/emojis) and [Unicode Full Emoji List](https://unicode.org/emoji/charts/full-emoji-list.html). * [:tv: Introducing Apple Vision Pro](https://www.youtube.com/watch?v=TX9qSaGXFyg) > 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](https://github.com/hack-different/mootool) > `mootool` is an attempt at an open source replacement to the legandary `jtool2` allowing it to continue to progress with the Apple research community. Ruby was selected as [Homebrew](https://brew.sh) 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](https://developer.apple.com/documentation/swiftui/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](https://developer.apple.com/support/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](https://developer.apple.com/videos/play/wwdc2023/10060), 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](https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_data_use_in_privacy_manifests) 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](https://www.plainswift.com) > Plain Swift is a simple development environment that allows you to develop executables and dynamic libraries using the [Swift programming language](https://www.swift.org/about). 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](https://www.cs.cornell.edu/andru/papers/gallifrey-types) > 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](https://chat.openai.com/g/g-veBqIkKIC-gerry-pass-ai) > Answers common recruiter & interview questions. * [Tracking preregistered images in 3D space](https://developer.apple.com/documentation/visionos/tracking-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](https://developer.apple.com/documentation/realitykit/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](https://developer.apple.com/documentation/realitykit/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](https://developer.apple.com/documentation/realitykit/capturing-photographs-for-realitykit-object-capture). * [Joker](https://newosxbook.com/tools/joker.html) > **Deprecated! The functionality of joker is now built-in to [Jtool2](http://newosxbook.com/tools/jtool2.tgz) 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(\_:)](https://developer.apple.com/documentation/swiftui/view/visualeffect3d(_:)) > _Applies effects to this view, while providing access to layout information through a 3D geometry proxy._ * [visualEffect(\_:)](https://developer.apple.com/documentation/swiftui/view/visualeffect(_:)) > _Applies effects to this view, while providing access to layout information through a geometry proxy._ * [GeometryReader3D](https://developer.apple.com/documentation/swiftui/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](https://developer.apple.com/documentation/swiftui/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](https://developer.apple.com/documentation/swiftui/zstack). * [Placing content on detected planes](https://developer.apple.com/documentation/visionos/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](https://marbla.de) > 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](https://www.swiftjectivec.com/calling-private-ios-apis-using-nsinvocation) > 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. > > 1. Find API To Invoke > 1. Import a Bundle > 1. Create a Class Type > 1. NSInvocation > 1. Run on your Device > * [**`Searching for iOS Headers`**](https://developer.limneos.net) * [MeshResource](https://developer.apple.com/documentation/realitykit/meshresource) > A high-level representation of a collection of vertices and edges that define a shape. * [`generateBox(size:majorCornerRadius:minorCornerRadius:)`](https://developer.apple.com/documentation/realitykit/meshresource/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](https://www.polpiella.dev/binary-swift-macros) > 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](https://www.createwithswift.com/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. > ## November * [NIO and Swift Concurrency](https://swiftpackageindex.com/apple/swift-nio/2.62.0/documentation/niocore/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](https://swiftpackageindex.com/apple/swift-nio/2.62.0/documentation/niocore/channel) eventing system and Swift’s Concurrency primitives as easy as possible. * [visionOS App Icon](https://developer.apple.com/design/human-interface-guidelines/app-icons#visionOS) > 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](https://developer.apple.com/documentation/Xcode/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](https://developer.apple.com/documentation/packagedescription/package/dependency/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](https://juripakaste.fi/swift-git-attributes) > **Step 1: Diff driver** > > Define a [diff driver](https://www.git-scm.com/docs/gitattributes#_defining_an_external_diff_driver) in your `$HOME/.gitconfig`. The `xfuncname` 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: > > ```git > [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 > 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: > > ```git > *.swift diff=swift > ``` > * [Join the Mac gaming revolution.](https://getwhisky.app) > **Wine _Supercharged..._** with the power of Apple's Game Porting Toolkit. * [Migrating a test from XCTest](https://swiftpackageindex.com/apple/swift-testing/main/documentation/testing/migratingfromxctest) > 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](https://nilcoalescing.com/blog/AsyncStreamFromWithObservationTrackingFunc) > I've been wondering if it would be possible to wrap observation into an `AsyncStream`. That would let me use an asynchronous `for` loop to iterate over changes. In this post I will share how I implemented it. * [SystemCoordinator](https://developer.apple.com/documentation/GroupActivities/SystemCoordinator) > _A type you use to coordinate your interface’s behavior when an active SharePlay session supports spatial placement of content._ > > A [`SystemCoordinator`](https://developer.apple.com/documentation/groupactivities/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 the [`SystemCoordinator`](https://developer.apple.com/documentation/groupactivities/systemcoordinator) object. > > You don’t create a [`SystemCoordinator`](https://developer.apple.com/documentation/groupactivities/systemcoordinator) object directly. After you receive a [`GroupSession`](https://developer.apple.com/documentation/groupactivities/groupsession) object for an activity, retrieve the system coordinator from the session’s [`systemCoordinator`](https://developer.apple.com/documentation/GroupActivities/GroupSession/systemCoordinator) property. When you first retrieve the object, update its [`configuration`](https://developer.apple.com/documentation/groupactivities/systemcoordinator/configuration-swift.property) 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](https://developer.apple.com/design/human-interface-guidelines/shareplay#visionOS) > 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](https://developer.apple.com/documentation/GroupActivities/SpatialTemplatePreference) > A structure that specifies the preferred arrangement of participant Spatial Personas in a shared simulation space. * [Peer-to-peer alternatives](https://developer.apple.com/documentation/technotes/tn3151-choosing-the-right-networking-api#Peer-to-peer-alternatives) > [Multipeer Connectivity](https://developer.apple.com/documentation/multipeerconnectivity) 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](https://developer.apple.com/documentation/network/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](https://developer.apple.com/documentation/technotes/tn3151-choosing-the-right-networking-api#Peer-to-peer-networking). > > Foundation also has peer-to-peer Wi-Fi support: > > * When advertising a service using NSNetService, set the [`includesPeerToPeer`](https://developer.apple.com/documentation/foundation/netservice/1414086-includespeertopeer) property. > * To accept connections, set the [`.listenForConnections`](https://developer.apple.com/documentation/foundation/netservice/options/1414270-listenforconnections) flag and implement the [`netService(_:didAcceptConnectionWith:outputStream:)`](https://developer.apple.com/documentation/foundation/netservicedelegate/1407489-netservice) delegate callback. > * When browsing for services using NSNetServiceBrowser, set the [`includesPeerToPeer`](https://developer.apple.com/documentation/foundation/netservicebrowser/1413106-includespeertopeer) property. > * After discovering a service with a peer-to-peer enabled browser, connect to that service using [`getInputStream(_:outputStream:)`](https://developer.apple.com/documentation/foundation/netservice/1418325-getinputstream). > > These APIs were marked as to-be-deprecated in 2021 (see [Versions](https://developer.apple.com/documentation/technotes/tn3151-choosing-the-right-networking-api#Versions)). If you have existing code that uses them, make a plan to migrate to [Network](https://developer.apple.com/documentation/network) framework. > > The [dnssd](https://developer.apple.com/documentation/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` or `NSNetService`. 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](https://developer.apple.com/documentation/technotes/tn3151-choosing-the-right-networking-api#Peer-to-peer-alternatives) > Apple platforms have a wide range of networking APIs, spanning many different frameworks: > > * [Foundation](https://developer.apple.com/documentation/foundation) > * [Network](https://developer.apple.com/documentation/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](https://developer.apple.com/documentation/technotes/tn3151-choosing-the-right-networking-api#Alternative-APIs) and some [Best practices](https://developer.apple.com/documentation/technotes/tn3151-choosing-the-right-networking-api#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](https://developer.apple.com/documentation/networkextension). * [How to customize the macOS menu bar in SwiftUI](https://danielsaidi.com/blog/2023/11/22/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`](https://developer.apple.com/documentation/swiftui/commandmenu) and [`CommandGroup`](https://developer.apple.com/documentation/swiftui/commandgroup). * [Spotlight on: Apple Vision Pro apps for enterprise](https://developer.apple.com/news/?id=n4yvry73) > 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](https://developer.apple.com/documentation/SwiftUI/UIHostingConfiguration) > _A content configuration suitable for hosting a hierarchy of SwiftUI views._ * [assumeIsolated(\_:file:line:)](https://developer.apple.com/documentation/swift/mainactor/assumeisolated(_:file:line:)-swift.type.method) > _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](https://developer.apple.com/documentation/swift/mainactor/sharedunownedexecutor-8ymny) as its own [unownedExecutor](https://developer.apple.com/documentation/swift/actor/unownedexecutor)–this check will succeed, as from a concurrency safety perspective, the serial executor guarantees mutual exclusion of those two actors. * [SwiftUIGPT](https://chat.openai.com/g/g-uCkV6rsVh-swiftuigpt) > Expert in SwiftUI, SwiftData, and Observation framework * [Elixir Phoenix Researcher](https://chat.openai.com/g/g-JbcoX4rVn-elixir-phoenix-researcher) > Expert in Elixir and Phoenix, uses official docs and forums for answers. * [AsyncGraphics](https://github.com/heestand-xyz/AsyncGraphics) > AsyncGraphics is a Swift package for working with images and video with async / await. The core type is simply just called [`Graphic`](https://heestand-xyz.github.io/AsyncGraphics-Docs/documentation/asyncgraphics/graphic), it's like an image and is backed by a [`MTLTexture`](https://developer.apple.com/documentation/metal/mtltexture). * [AsyncStream.Continuation](https://developer.apple.com/documentation/swift/asyncstream/continuation) > _A mechanism to interface between synchronous code and an asynchronous stream._ > > The closure you provide to the `AsyncStream` in `init(_:bufferingPolicy:\_:)` receives an instance of this type when invoked. Use this continuation to provide elements to the stream by calling one of the `yield` methods, then terminate the stream normally by calling the `finish()` method. > > **Note:** > Unlike other continuations in Swift, AsyncStream.Continuation supports escaping. * [Designing custom gestures in visionOS](https://developer.apple.com/design/human-interface-guidelines/gestures/#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](https://developer.apple.com/documentation/visionOS/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](https://developer.apple.com/documentation/arkit/handtrackingprovider) > A source of live data about the position of a person’s hands and hand joints. * [Introducing Inferno: Metal shaders for SwiftUI](https://www.hackingwithswift.com/articles/262/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](https://www.hackingwithswift.com/quick-start/swiftui/how-to-add-metal-shaders-to-swiftui-views-using-layer-effects), 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](https://github.com/twostraws/Inferno), 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](https://youtu.be/EgzWwgRpUuw) 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](https://wojciechkulik.pl/ios/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**](https://pkgx.sh) > `pkgx` is a blazingly fast, standalone, cross‐platform binary that _runs anything_ * [values](https://developer.apple.com/documentation/combine/publisher/values-1dm9r) > _The elements produced by the publisher, as an asynchronous sequence._ > > This property provides an [AsyncPublisher](https://developer.apple.com/documentation/combine/asyncpublisher), which allows you to use the Swift async-await syntax to receive the publisher’s elements. Because [AsyncPublisher](https://developer.apple.com/documentation/combine/asyncpublisher) conforms to [AsyncSequence](https://developer.apple.com/documentation/Swift/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(\_:)](https://developer.apple.com/documentation/combine/publisher/filter(_:)) operator’s documentation, which filters a sequence to only emit even integers. This example replaces the [Subscribers.Sink](https://developer.apple.com/documentation/combine/subscribers/sink) subscriber with a for-await-in loop that iterates over the [AsyncPublisher](https://developer.apple.com/documentation/combine/asyncpublisher) provided by the values property. ```swift 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](https://developer.apple.com/documentation/combine/asyncpublisher) > _A publisher that exposes its elements as an asynchronous sequence._ > > AsyncPublisher conforms to [AsyncSequence](https://developer.apple.com/documentation/Swift/AsyncSequence), which allows callers to receive values with the for-await-in syntax, rather than attaching a [Subscriber](https://developer.apple.com/documentation/combine/subscriber). > > Use the [values](https://developer.apple.com/documentation/combine/publisher/values-1dm9r) property of the [Publisher](https://developer.apple.com/documentation/combine/publisher) protocol to wrap an existing publisher with an instance of this type. * [viewIsAppearing(\_:)](https://developer.apple.com/documentation/uikit/uiviewcontroller/4195485-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(\_:)](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621510-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](https://developer.apple.com/documentation/swiftui/previews-in-xcode) > _Generate dynamic, interactive previews of your custom views._ > > When you create a custom [View](https://developer.apple.com/documentation/swiftui/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:)](https://developer.apple.com/documentation/swiftui/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:)](https://developer.apple.com/documentation/swiftui/preview(_:traits:_:body:)) macro or add custom viewpoints for the preview using the [Preview(\_:traits:body:cameras:)](https://developer.apple.com/documentation/swiftui/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:)](https://developer.apple.com/documentation/swiftui/preview(_:immersionstyle:traits:body:)) macro to preview your view inside an [ImmersiveSpace](https://developer.apple.com/documentation/swiftui/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](https://developer.apple.com/documentation/swiftui/previewprovider) protocol and its associated supporting types to define and configure a preview. * [Immersive spaces](https://developer.apple.com/documentation/swiftui/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](https://developer.apple.com/documentation/RealityKit/RealityView) to present RealityKit content. > > You can request one of three styles of spaces with the [immersionStyle(selection:in:)](https://developer.apple.com/documentation/swiftui/scene/immersionstyle(selection:in:)) scene modifier: > * The [mixed](https://developer.apple.com/documentation/swiftui/immersionstyle/mixed) style blends your content with passthrough. This enables you to place virtual objects in a person’s surroundings. > * The [full](https://developer.apple.com/documentation/swiftui/immersionstyle/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](https://developer.apple.com/documentation/swiftui/immersionstyle/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](https://developer.apple.com/documentation/swiftui/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](https://developer.apple.com/documentation/swiftui/canvas) that has an ongoing spatial event: ```swift 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](https://developer.apple.com/documentation/swiftui/spatialeventcollection) structure when it detects changes. The collection contains [SpatialEventCollection.Event](https://developer.apple.com/documentation/swiftui/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](https://developer.apple.com/documentation/swiftui/spatialeventcollection/event/phase-swift.enum/ended) or [SpatialEventCollection.Event.Phase.cancelled](https://developer.apple.com/documentation/swiftui/spatialeventcollection/event/phase-swift.enum/cancelled) while the gesture itself remains active. Individually track state for each event inside [onChanged(\_:)](https://developer.apple.com/documentation/swiftui/gesture/onchanged(_:)) or [updating(\_:body:)](https://developer.apple.com/documentation/swiftui/gesture/updating(_:body:)) and clean up all state in [onEnded(\_:)](https://developer.apple.com/documentation/swiftui/gesture/onended(_:)). * [Tim — Your iOS Mobile Dev Interview Coach](https://chat.openai.com/g/g-Bq6IZuAxd-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](https://chat.openai.com/g/g-G5diVh12v-chatprd) > An on-demand Chief Product Officer that drafts and improves your PRDs, while coaching you to become an elite product manager. * [XcodeGPT](https://chat.openai.com/g/g-z9dLWHPID-xcodegpt) > Your Xcode assistant with a new logo * [NSBundleResourceRequest](https://developer.apple.com/documentation/foundation/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:)](https://developer.apple.com/documentation/foundation/nsbundleresourcerequest/1614840-beginaccessingresources) or [conditionallyBeginAccessingResources(completionHandler:)](https://developer.apple.com/documentation/foundation/nsbundleresourcerequest/1614834-conditionallybeginaccessingresou) is called successfully. Management ends after a call to [endAccessingResources()](https://developer.apple.com/documentation/foundation/nsbundleresourcerequest/1614843-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](https://developer.apple.com/documentation/foundation/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:)](https://developer.apple.com/documentation/foundation/bundle/1614845-setpreservationpriority) and [preservationPriority(forTag:)](https://developer.apple.com/documentation/foundation/bundle/1614839-preservationpriority). * [XcodeGPT](https://tuist.io/blog/2023/11/10/gpts) > 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](https://chat.openai.com/g/g-z9dLWHPID-xcodegpt). * [Adopting the system player interface in visionOS](https://developer.apple.com/documentation/avkit/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](https://developer.apple.com/documentation/avkit/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](https://developer.apple.com/documentation/visionos/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](https://developer.apple.com/documentation/SwiftUI/WindowStyle/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?](https://betterprogramming.pub/geometryreader-blessing-or-curse-1ebd2d5005ec) > 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](https://chat.openai.com/g/g-1ex7nJso7-swiftie) > **An expert Swift developer at your service*** > > _*Requires ChatGPT Plus_ * [**Reasync.swift**](https://github.com/pointfreeco/swift-concurrency-extras/blob/1676c3b73e1657b9e91f0ca8194855eee4138006/Sources/ConcurrencyExtras/Result.swift) ```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`](https://github.com/apple/swift/blob/main/docs/TransparentAttr.md#_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. * [Fucking Format Style!](https://fuckingformatstyle.com) > **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. * [Integrating Swift Macros with Xcodeproj native blocks](https://pepicrft.me/blog/2023/11/08/swift-macros-with-xcodeproj-native-blocks) > [Swift Macros](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/macros) were introduced by Apple as a feature bundled within Swift Packages. This approach enhances shareability—a notable limitation of [XcodeProj](https://github.com/tuist/xcodeproj) elements like [targets](https://github.com/tuist/XcodeProj/blob/main/Sources/XcodeProj/Objects/Targets/PBXNativeTarget.swift). 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](https://bazel.build) quickly [devised a method to accommodate Swift Macros using compiler flags](https://github.com/bazelbuild/rules_swift/pull/1061). 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](https://www.swift.org/blog/swift-5.9-backtraces) > 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](https://automerge.org/blog/2023/11/06/automerge-repo) > Today we are announcing our new library, [`automerge-repo`](https://github.com/automerge/automerge-repo), which makes it vastly easier to build local-first applications with Automerge. Take a look at our [quickstart guide](https://automerge.org/docs/quickstart) 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](https://inkandswitch.com/local-first), or watch a [talk introducing the idea](https://www.youtube.com/watch?v=PHz17gwiOc8). > > A challenge in local-first software is how to merge edits that were made independently on different devices, and [CRDTs](https://crdt.tech) 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](https://dev.to/jakub_zalas/functional-event-sourcing-example-in-kotlin-3245) > 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](https://marioaguzman.github.io/design/layoutguidelines) > 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`](https://developer.apple.com/documentation/swift/character/isnewline) > _A Boolean value indicating whether this character represents a newline._ * [TN3135: Low-level networking on watchOS](https://developer.apple.com/documentation/technotes/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](https://developer.apple.com/documentation/foundation/urlsession), and any code layered on top of that. > * Low-level networking. This includes [Network](https://developer.apple.com/documentation/network) framework, [NSStream](https://developer.apple.com/documentation/foundation/nsstream), and any other API that runs a TCP connection or UDP session directly. That includes the low-level aspects of [URLSession](https://developer.apple.com/documentation/foundation/urlsession), namely [URLSessionStreamTask](https://developer.apple.com/documentation/foundation/urlsessionstreamtask) and [URLSessionWebSocketTask](https://developer.apple.com/documentation/foundation/urlsessionwebsockettask). It also includes APIs, like [NWBrowser](https://developer.apple.com/documentation/network/nwbrowser) and [NSNetService](https://developer.apple.com/documentation/foundation/netservice), 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](https://developer.apple.com/documentation/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](https://developer.apple.com/documentation/devicediscoveryui) framework. Support for this was added in watchOS 9 and tvOS 16. > * [Bonjour](https://developer.apple.com/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](https://support.apple.com/en-gb/guide/iphone/iph21c29a1cf/ios) > 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](https://nilcoalescing.com/blog/HierarchicalBackgroundStyles) > Starting from iOS 17 we now have new properties, such as [secondary](https://developer.apple.com/documentation/swiftui/shapestyle/secondary-swift.property), [tertiary](https://developer.apple.com/documentation/swiftui/shapestyle/tertiary-swift.property), [quaternary](https://developer.apple.com/documentation/swiftui/shapestyle/quaternary-swift.property) and [quinary](https://developer.apple.com/documentation/swiftui/shapestyle/quinary-swift.property) 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 to `ShapeStyle` protocol, so accessing the `secondary` property on an instance of a `BackgroundStyle` 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 on `ShapeStyle`. * [macOS Containers](https://macoscontainers.org) > 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](https://developer.apple.com/documentation/visionos/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](https://orion.tube) > Finally, a display that can go with you _anywhere._ > > Orion turns iPad into your portable HDMI Monitor. * [New Computer](https://new.computer) > Dot by New Computer is an intelligent guide designed to help you remember, organize, and navigate your life. * [Swift Packages](https://www.swift.org/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](https://www.swift.org/package-manager) (SwiftPM). * [More Data Types with Negation at Fun in the REPL](https://bentnib.org/posts/2023-11-02-more-data-types-with-negation.html) > 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): ```agda data Even : Nat → Set where zero : Even 0 suc : ∀ {n} → not (Even n) → Even (suc n) ``` > So `0` is even, and `suc n` is even if `n` isn't. > > But if we get this to work, then what would this declaration mean? ```agda data Liar : Set where liar : not Liar → Liar ``` * [Misty Programming Language](https://www.crockford.com/misty) > 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](http://www.crockford.com/mckeeman.html). * [Machine learning of GUIs at scale](https://austinhenley.com/blog/machinelearningguis.html) > 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! > ## October * [GitHub Tip: using the involves filter](https://www.jessesquires.com/blog/2023/10/30/github-tip-filter-involves) > 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`**](https://docs.github.com/en/search-github/searching-on-github/searching-issues-and-pull-requests#search-by-a-user-thats-involved-in-an-issue-or-pull-request), 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](https://speakinginswift.substack.com/p/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](https://jacobbartlett.substack.com/p/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](https://skip.tools) > 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](https://skip.tools/tour) or browse the [documentation](https://skip.tools/docs). * [Figma Event Storming template](https://www.figma.com/file/tmlkr4bccZtUvKSXVI4NCa/Event-storming-(Copy)) > 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](https://machinelearning.apple.com/research/neural-engine-transformers) > An increasing number of the machine learning (ML) models we build at Apple each year are either partly or fully adopting the [Transformer architecture](https://arxiv.org/abs/1706.03762). This architecture helps enable experiences such as [panoptic segmentation in Camera with HyperDETR](https://machinelearning.apple.com/research/panoptic-segmentation), [on-device scene analysis in Photos](https://machinelearning.apple.com/research/on-device-scene-analysis), [image captioning for accessibility](https://support.apple.com/guide/iphone/use-voiceover-for-images-and-videos-iph37e6b3844/ios), [machine translation](https://apps.apple.com/us/app/translate/id1514844618), and many others. This year at WWDC 2022, Apple is making available an open-source reference [PyTorch](https://pytorch.org) 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](https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english), 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!](https://skingenerator.io) > 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](https://developer.apple.com/forums/thread/738840) > 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](https://ileakage.com) > 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](https://developer.apple.com/documentation/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](https://developer.apple.com/documentation/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](https://developer.apple.com/documentation/visionos/understanding-the-realitykit-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](https://developer.apple.com/documentation/RealityKit/Entity), you can add the same components to both of them and give them the same behavior or functionality. * [Spatial layout](https://developer.apple.com/design/human-interface-guidelines/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](https://developer.apple.com/design/human-interface-guidelines/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](https://developer.apple.com/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](https://ducklet.app) > The fast, native SQLite database editor for macOS. * [Spatial](https://developer.apple.com/documentation/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)](https://developer.apple.com/videos/play/wwdc2021/10254) > 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**](https://developer.apple.com/documentation/realitykit/videoplayercomponent) > In visionOS, the `VideoPlayerComponent` is another way to create a video scene (including for HEVC video with transparency). * [Designing for visionOS](https://developer.apple.com/design/human-interface-guidelines/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](https://developer.apple.com/design/human-interface-guidelines/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](https://developer.apple.com/documentation/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](https://developer.apple.com/documentation/avkit/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](https://developer.apple.com/documentation/RealityKit). * [Playing audio — visionOS](https://developer.apple.com/design/human-interface-guidelines/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!](https://mountaintown.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](https://developer.apple.com/documentation/realitykit/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](https://support.apple.com/guide/deployment/welcome/1/web) > 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. > > See [What’s new in Apple Platform Deployment >](https://support.apple.com/guide/deployment/whats-new-dep950aed53e/1/web/1.0) * [Introducing Insights, and new pricing](https://revealapp.com/news/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](https://leanprover-community.github.io/install/macos_details.html) > This document explains a more controlled installation procedure for Lean on MacOS. There is a quicker way described in the main [install page](https://leanprover-community.github.io/install/macos.html) but it requires more trust. * [Destination Video](https://developer.apple.com/documentation/visionos/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](https://developer.apple.com/documentation/visionos/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](https://developer.apple.com/documentation/realitykit/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](https://developer.apple.com/documentation/avfoundation/avplayer) instance to control movie playback. You can use any movie file format that [AVPlayer](https://developer.apple.com/documentation/avfoundation/avplayer) supports to create a video material. To control playback of the material’s video, use the [avPlayer](https://developer.apple.com/documentation/realitykit/videomaterial/avplayer) property, which offers methods like [play()](https://developer.apple.com/documentation/avfoundation/avplayer/1386726-play) and [pause()](https://developer.apple.com/documentation/avfoundation/avplayer/1387895-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](https://docs.github.com/en/enterprise-cloud@latest/organizations/managing-organization-settings/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](https://jackrusher.com/pwl-2023) > This is going to be an unusual [Papers We Love](https://pwlconf.org) 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](https://jackrusher.com/strange-loop-2022) 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](https://www.mothersruin.com/software/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](https://github.com/mlc-ai/mlc-llm/blob/85001ed4b722ee99ab2329e1b2604650934cc49b/docs/deploy/ios.rst#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](https://exoplanets.nasa.gov/alien-worlds/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](https://developer.apple.com/documentation/foundation/processinfo/3608556-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 is `false` for all other apps on the Mac, including Mac apps built using Mac Catalyst. The property is also `false` for processes running on platforms other than macOS. * [EffectsLibrary tutorials](https://swiftpackageindex.com/getstream/effects-library/main/tutorials/tutorial-table) > 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](https://swiftpackageindex.com/chimehq/swifttreesitter/0.7.2/tutorials/using-tree-sitter) > 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](https://www.codewithkasetti.com/posts/swiftformat_integration_automation) > 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](https://developer.apple.com/documentation/visionos/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](https://tart.run) > **Tart** is a virtualization toolset to build, run and manage _macOS_ and _Linux_ virtual machines on _Apple Silicon_. * [Pijul](https://nest.pijul.com/pijul/pijul) > A sound and fast distributed version control system based on a mathematical theory of asynchronous work. * [Conditional Xcode Build Settings](https://indiestack.com/2023/10/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](https://developer.apple.com/documentation/xcode/adding-a-build-configuration-file-to-your-project). 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](https://boringtechnology.club) > This is the spoken word version of my essay, [Choose Boring Technology](http://mcfunley.com/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](https://twitter.com/cscottnet) called it “how to be old, for young people.” Here are [my other talks](https://speakerdeck.com/mcfunley), [my website](http://mcfunley.com), and [some Medium posts](https://medium.com/@mcfunley/latest). ## September * [PROJEKT: OVERFLOW — RISC-V assembly board game](https://punkx.org/overflow) > 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](http://phrack.org/issues/49/14.html#article) 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](https://en.wikipedia.org/wiki/Preemption_(computing)) 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](https://www.swift.org/blog/whats-new-swift-debugging-5.9) > **Faster variable inspection with `p` and `po`** > > 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 heavyweight `expression` and `expression -O` commands. In Swift 5.9, the `p` and `po` command aliases have been redefined to the new [dwim-print command](https://reviews.llvm.org/D138315). > > 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 as `frame variable` or `v` instead of the more expensive expression evaluator. > > In addition to being faster, using `p` [no longer creates persistent result variables](https://reviews.llvm.org/D145609) 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 expressions** > > LLDB now supports referring to generic type parameters in expression evaluation. For example, given the following code: ```swift func use<T>(_ t: T) { print(t) // break here } use(5) use("Hello!") ``` > Running `po T.self`, when stopped in use, will print `Int` when coming in through the first call, and `String` 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: ```swift 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)](https://github.com/twitter/ios-twitter-network-layer) > 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](https://developer.apple.com/documentation/visionos/interacting-with-your-app-in-the-visionos-simulator) > #### Interact with your appin page link > > 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. > > #### Navigate the spacein page link > > 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](https://developer.apple.com/documentation/visionos/understanding-the-realitykit-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](https://developer.apple.com/documentation/RealityKit/Entity), you can add the same components to both of them and give them the same behavior or functionality. * [Bezel](https://getbezel.app) > _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](https://www.anthropic.com/index/prompting-long-context) > Claude’s [100,000 token long context window enables](https://www.anthropic.com/index/100k-context-windows) the model to operate over hundreds of pages of technical documentation, or even an [entire book](https://twitter.com/AnthropicAI/status/1656700156518060033). 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](https://github.com/apple/swift-testing/blob/main/Documentation/Vision.md) > 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?](https://dev.to/tigt/why-not-react-2f8l) > 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](https://twitter.com/sebmarkbage/status/1516907614566854659). And finally, [longstanding evidence holds React trends antagonistic towards performance](https://timkadlec.com/remembers/2020-04-21-the-cost-of-javascript-frameworks). > > _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](https://twitter.com/dan_abramov/status/1259614150386425858). 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?** * [A different way to build together](https://pierre.co) > 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](https://browsercompany.substack.com/cp/137231709) > 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](https://machinelearning.apple.com/research/neural-engine-transformers) > An increasing number of the machine learning (ML) models we build at Apple each year are either partly or fully adopting the [Transformer architecture](https://arxiv.org/abs/1706.03762). This architecture helps enable experiences such as [panoptic segmentation in Camera with HyperDETR](https://machinelearning.apple.com/research/panoptic-segmentation), [on-device scene analysis in Photos](https://machinelearning.apple.com/research/on-device-scene-analysis), [image captioning for accessibility](https://support.apple.com/guide/iphone/use-voiceover-for-images-and-videos-iph37e6b3844/ios), [machine translation](https://apps.apple.com/us/app/translate/id1514844618), and many others. This year at WWDC 2022, Apple is making available an open-source reference [PyTorch](https://pytorch.org) 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](https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english), 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](https://forums.swift.org/t/precise-error-typing-in-swift/52045) > 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 throwing `Error`. > > 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**](https://github.com/pointfreeco/swift-macro-testing) > Magical testing tools for Swift macros. * [**Swift Version**](https://swiftversion.net) * [SQL join flavors](https://antonz.org/sql-join) > There is more to SQL joins than you might think. Let's explore them a bit. > * [Qualified join](https://antonz.org/sql-join/#qualified-join) > * [Natural join](https://antonz.org/sql-join/#natural-join) > * [Cross join](https://antonz.org/sql-join/#cross-join) > * [Partitioned join](https://antonz.org/sql-join/#partitioned-join) > * [Lateral join](https://antonz.org/sql-join/#lateral-join) > * [Summary](https://antonz.org/sql-join/#summary) * [Access-level modifiers on import declarations [SE-0409]](https://github.com/apple/swift-evolution/blob/main/proposals/0409-access-level-on-imports.md) > **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`, and `private`. > > A public dependency can be referenced from any declaration and will be visible to all clients. It is declared with the `public` modifier. ```swift public import PublicDependency ``` > A dependency visible only to the modules of the same package is declared with the `package` modifier. Only the signature of `package`, `internal`, `fileprivate` and `private` declarations can reference the imported module. ```swift package import PackageDependency ``` > A dependency internal to the module is declared with the `internal` modifier. Only the signature of `internal`, `fileprivate` and `private` declarations can reference the imported module. ```swift internal import InternalDependency ``` > A dependency private to this source file is declared with either the `fileprivate` or the `private` modifier. In both cases the access is scoped to the source file declaring the import. Only the signature of `fileprivate` and `private` declarations can reference the imported module. ```swift 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](https://engineering.traderepublic.com/easy-self-hosted-ci-on-apple-silicon-with-cilicon-6e7d9503c2d6) > **TL;DR:** We released a new macOS app called [**Cilicon**](https://github.com/traderepublic/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](https://huggingface.co/blog/swift-coreml-llm) > 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](https://chris.eidhof.nl/post/view-representable) > 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](https://simonbs.dev/posts/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](https://support.apple.com/en-us/HT211145). 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](https://developer.apple.com/forums/thread/113742) > **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)](https://www.emergetools.com/blog/posts/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](https://useyourloaf.com/blog/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](https://jfrog.com/blog/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](https://jfrog.com/artifactory) 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?](https://forums.swift.org/t/is-dispatchprecondition-a-reasonable-way-to-implement-an-unchecked-sendable-type/67159/10) > 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 be `Sendable`. > * 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. > * [Selective.kt](https://web.archive.org/web/20190623213927/https://github.com/arrow-kt/arrow/blob/master/modules/core/arrow-core-data/src/main/kotlin/arrow/typeclasses/Selective.kt) ```kotlin 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](https://chris.eidhof.nl/presentations/day-in-the-life) > 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.](https://www.mobilesystemdesign.com) > Improve the way you work and strengthen your skills as an experienced mobile engineer. > ## August * [TECH STACK AT AMO](https://about.amo.co/the-amo-tech-stack) > 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](https://bazel.build) (an open-source port of Google Blaze). * [What's nonce entanglement?](https://gist.github.com/m1stadev/5464ea557c2b999cb9324639c777cd09) > 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](https://chris.eidhof.nl/post/visualize-swiftui-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](https://www.swiftbysundell.com/articles/swifts-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](https://developer.apple.com/documentation/foundation/url_loading_system/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](https://developer.apple.com/documentation/foundation/urlsessionuploadtask) (a subclass of [URLSessionTask](https://developer.apple.com/documentation/foundation/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**](https://osstatus.com) > Look up Apple API errors quickly! * [How to check if you use a required reason API](https://blog.eidinger.info/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](https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_use_of_required_reason_api). * [Migrating from the Observable Object protocol to the Observable macro](https://developer.apple.com/documentation/swiftui/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](https://www.manu.show/2023-08-18-improve-build-times-in-spm-packages-and-in-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](https://www.manu.show/2023-08-18-improve-build-times-in-spm-packages-and-in-your-apps/#improve-compile-time-in-xcode-projects) section > * Check the [Improve Compile Time in SPM Packages](https://www.manu.show/2023-08-18-improve-build-times-in-spm-packages-and-in-your-apps/#improve-compile-time-in-spm-packages) section > * Check the [Build with Timing Summary + Recent Build TimeLine](https://www.manu.show/2023-08-18-improve-build-times-in-spm-packages-and-in-your-apps/#build-with-timing-summary-and-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](https://www.manu.show/2023-08-18-improve-build-times-in-spm-packages-and-in-your-apps/#build-with-timing-summary-and-recent-build-timeline) section > * [Representing haptic patterns in AHAP files](https://developer.apple.com/documentation/corehaptics/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](https://www.swiftedmind.com/blog/posts/meet-puddles/introducing-puddles) > 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](https://www.swiftedmind.com/puddles) or in the [repository](https://www.swiftedmind.com/github/puddles). 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?](http://blog.sigfpe.com/2023/08/what-does-it-mean-for-monad-to-be-strong.html) > 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 of `strength` 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](https://forums.swift.org/t/explicit-module-builds-the-new-swift-driver-and-swiftpm/36990) > _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](https://khanlou.com/2018/11/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](https://theswiftdev.com/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](https://journal.infinitenegativeutility.com/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](https://github.com/obsidiansystems/dependent-sum) > Dependent sums and supporting typeclasses for comparing and displaying them * [dependent-map](https://github.com/obsidiansystems/dependent-map) > This library defines a dependently-typed finite map type. It is derived from `Data.Map.Map` in the `containers` package, but rather than (conceptually) storing pairs indexed by the first component, it stores `DSum`s (from the `dependent-sum` package) indexed by tag. * [macOS 0day: App Management](https://lapcatsoftware.com/articles/2023/8/2.html) > 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](https://lapcatsoftware.com/articles/downloads/AppManagementBug.zip). * [An introduction to fibrations, topos theory, the effective topos and modest sets](http://www.lfcs.inf.ed.ac.uk/reports/92/ECS-LFCS-92-208) > _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](https://www.emergetools.com/blog/posts/SwiftReferenceTypes) > 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](https://developer.apple.com/videos/play/wwdc2019/423/?time=305) 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](https://www.emergetools.com), 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](https://www.emergetools.com/blog/posts/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](https://www.openrefactory.com/intelligent-code-repair-icr/#:~:text=On%20average%2C%20a%20developer%20creates,writing%20a%20line%20of%20code). > > There are even performance implications for having dead code take up memory in your iOS app, which I’ve mentioned in articles about [fixups](https://www.emergetools.com/blog/posts/SwiftReferenceTypes) and [order files](https://www.emergetools.com/blog/posts/FasterAppStartupOrderFiles). Emerge helps reduce the complexity of apps and infrastructure, including by finding dead code such as [protocols without any conformances](https://docs.emergetools.com/docs/unused-protocols). This is done with static analysis. > > [Reaper](https://docs.emergetools.com/docs/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](https://docs.emergetools.com/docs/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](https://surma.dev/things/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](https://kcomposite.com/product/money/?mc_cid=b88368ea22) > 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](https://www.openterraform.io) > 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](https://forums.swift.org/c/related-projects/grdb/36) > 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?](https://github.com/groue/GRDB.swift/blob/master/Documentation/WhyAdoptGRDB.md) 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](https://holyswift.app/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?](https://langdev.stackexchange.com/questions/2692/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.](https://layerform.dev) > _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:)](https://developer.apple.com/documentation/webkit/wkwebview/3650490-createpdf) > _Generates PDF data from the web view’s contents asynchronously._ * [Compositionality](https://compositionality-journal.org) > 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](https://compositionality-journal.org/about). * [Mermaid by Miro Labs](https://miro.com/marketplace/mermaid) > 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](https://github.com/apple/swift-evolution/blob/main/proposals/0337-support-incremental-migration-to-concurrency-checking.md) > Swift 5.5 introduced mechanisms to eliminate data races from the language, including the `Sendable` protocol ([SE-0302](https://github.com/apple/swift-evolution/blob/main/proposals/0302-concurrent-value-and-concurrent-closures.md)) to indicate which types have values that can safely be used across task and actor boundaries, and global actors ([SE-0316](https://github.com/apple/swift-evolution/blob/main/proposals/0316-global-actors.md)) to help ensure proper synchronization with (e.g.) the main actor. However, Swift 5.5 does not fully enforce `Sendable` 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](https://forums.swift.org/t/pitch-staging-in-sendable-checking/51341), [Pitch #2](https://forums.swift.org/t/pitch-2-staging-in-sendable-checking/52413), [Pitch #3](https://forums.swift.org/t/pitch-3-incremental-migration-to-concurrency-checking/53610) * [Mermaid Event Storming](https://devrants.blog/2022/08/20/mermaid-event-storming) ```mermaid 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](https://alwaysprocessing.blog/series/objc-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]](https://github.com/apple/swift-package-manager/blob/main/Documentation/Plugins.md) > 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](https://www.davidchudzicki.com/posts/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](https://www.modellution.com) > Best collaboration platform for Event Storming & Event Modeling * [Flipper Zero](https://flipperzero.one) > _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)](https://github.com/orgs/community/discussions/16925) ``` > [!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](https://www.sdf.com) > _SDF does for SQL what Typescript did for Javascript. Faster Development. Trusted Results. Safety at Scale._ * [Swift Compiler Performance](https://github.com/apple/swift/blob/main/docs/CompilerPerformance.md#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](https://github.com/c4710n/TSPL-doccarchive) > Visit the history versions of [TSPL(The Swift Programming Language)](https://github.com/apple/swift-book) with ease. * [Obstructions to Compositionality](https://arxiv.org/abs/2307.14461) > 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](https://arxiv.org/html/2307.15519v1/#EPTCS380.0) > 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](https://www.kodeco.com/40047657-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](https://github.com/DougGregor/swift-evolution/blob/function-body-macros/proposals/nnnn-function-body-macros.md) > This proposal introduces _function body macros_, which are [attached macros](https://github.com/apple/swift-evolution/blob/main/proposals/0389-attached-macros.md) that can create or augment a function (including initializers, deinitializers, and accessors) with a new body. * [swift server + dev containers](https://jagreenwood.github.io/posts/swift-devcontainers) > 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](https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/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](https://lean-fro.org) > 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](https://leanprover.github.io). Our 5-year mission is to empower Lean towards self-sustainability. * [Push Notifications Options in SwiftUI](https://holyswift.app/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.](https://www.cs.bham.ac.uk/~mhe/TypeTopology/Iterative.index.html) > 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](https://xcode.tips/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. > >  > ## July * [Format Styles In Excruciating Detail](https://goshdarnformatstyle.com) > 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. * [Developer Duck AI for Xcode](https://apps.apple.com/app/id1662283032) > _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](https://tanaschita.com/20230717-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](https://betterprogramming.pub/how-to-use-swift-package-manager-saving-gigabytes-of-network-traffic-and-disk-space-998bd148ad56) > Use SPM to store dependency checkouts in a repository and do it better than CocoaPods * [JavaScript Macros in Bun](https://bun.sh/blog/bun-macros) > 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](https://okmij.org/ftp/continuations/stack-env.html) > 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](https://aws-samples.github.io/aws-sam-swift) > The [AWS Serverless Application Model (SAM)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-specification.html) 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](https://aws.amazon.com/lambda) Functions written in Swift. The functions use the [AWS SDK for Swift](https://docs.aws.amazon.com/sdk-for-swift/latest/developer-guide/getting-started.html) and the [Swift AWS Lambda Runtime](https://github.com/swift-server/swift-aws-lambda-runtime). * [OrbStack — Say goodbye to slow, clunky containers and VMs](https://orbstack.dev) > Seamless and efficient Docker and Linux on your Mac. Glide through your work faster with our Docker Desktop alternative. * [Understanding SVG Paths](https://www.nan.fyi/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 cryptic `d` attribute. * [ClamXAV — Put a stop to malware, not to your Mac](https://www.clamxav.com) > Keep your Mac safe with ClamXAV, the trusted anti-virus and malware scanner for macoS * [Uxn](https://100r.co/site/uxn.html) > The Uxn ecosystem is a little **personal computing stack**, created to host ours tools and games, programmable in its own unique [assembly language](https://wiki.xxiivv.com/site/uxntal.html). > > 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](https://100r.co/site/uxn_design.html), see the [VM specs](https://wiki.xxiivv.com/site/uxn.html), or the [IO specs](https://wiki.xxiivv.com/site/varvara.html). * [Timely Computation — Conal Elliott](http://conal.net/papers/timely-computation) > 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](https://www.nwf.org/nativeplantfinder) > 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](https://www.humancode.us/2023/07/08/all-about-nsitemprovider.html) > 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](https://www.digitalocean.com/community/tutorials/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](https://troz.net/post/2023/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. > ## June * [One-shot Algebraic Effects in Swift](https://forums.swift.org/t/algebraic-effects/38769/24) > 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 use `withCheckedContinuation` to access the current handler and resume the task with the result: > ```swift 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](https://developer.apple.com/documentation/swiftui/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](https://saurabhs.org/advanced-macos-commands) > 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](https://github.com/lean-dojo/LeanDojo) > [LeanDojo](https://leandojo.org) is a Python library for learning–based theorem provers in Lean, supporting both [Lean 3](https://github.com/leanprover-community/lean) and [Lean 4](https://leanprover.github.io). It provides two main features: > > * Extracting data (proof states, tactics, premises, etc.) from Lean repos. > * Interacting with Lean programmatically. > * [Swift values and locations](https://forums.swift.org/t/second-review-se-0395-observability/65261/119) > 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, and `struct`s can broken down recursively into the component values they store in their stored properties. For example, I might say that a particular value is `Ball(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](https://openpm.ai) > 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](https://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](https://config.figma.com/video-on-demand?slug=6329872286112) > 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](https://developer.apple.com/design/human-interface-guidelines/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](https://developer.apple.com/design/human-interface-guidelines/windows), [volumes](https://developer.apple.com/design/human-interface-guidelines/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](https://developer.apple.com/design/human-interface-guidelines/immersive-experiences). 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](https://developer.apple.com/design/human-interface-guidelines/immersive-experiences#Immersion-and-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](https://developer.apple.com/design/human-interface-guidelines/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](https://developer.apple.com/design/human-interface-guidelines/playing-audio#visionOS) to bring custom experiences to life. > > **Focus and gestures.** In general, people interact with Vision Pro using their [eyes](https://developer.apple.com/design/human-interface-guidelines/eyes) and [hands](https://developer.apple.com/design/human-interface-guidelines/gestures#visionOS). People perform most actions by looking at a virtual object to bring [focus](https://developer.apple.com/design/human-interface-guidelines/focus-and-selection) 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](https://developer.apple.com/design/human-interface-guidelines/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](https://www.figma.com/community/file/1253443272911187215) > 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](https://developer.apple.com/sf-symbols) before using this library. * [Cross-module inlining and specialization](https://github.com/apple/swift-evolution/blob/main/proposals/0193-cross-module-inlining-and-specialization.md) > 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](https://github.com/devMEremenko/XcodeBenchmark) > `XcodeBenchmark` contains a _large_ codebase to measure the compilation time in Xcode. * [What was special about Pivotal?](https://www.simplermachines.com/mr-reciprocity) > **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](https://sarunw.com/posts/little-big-improvements-xcode15) > > 1. [Better code completion for methods with many default parameters](https://sarunw.com/posts/little-big-improvements-xcode15/#methods-with-many-default-parameters). > 1. [Context awareness](https://sarunw.com/posts/little-big-improvements-xcode15/#context-awareness). > 1. [Documentation Preview](https://sarunw.com/posts/little-big-improvements-xcode15/#documentation-preview). > 1. [Quick Action](https://sarunw.com/posts/little-big-improvements-xcode15/#quick-action). > 1. [Bookmark](https://sarunw.com/posts/little-big-improvements-xcode15/#bookmark). > 1. [Format to Multiple Lines](https://sarunw.com/posts/little-big-improvements-xcode15/#format-to-multiple-lines). > * [BuildSettingExtractor](https://buildsettingextractor.com) > **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](https://midnight-beanie-ccb.notion.site/WWDC23-SwiftUI-520489da7e914cd18b5f5e43eeeec069) > _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](https://nilcoalescing.com/blog/ForegroundStyleInsideTextInSwiftUI) > SwiftUI lets us style portions of text by interpolating `Text` inside another `Text` and applying available text modifiers, such as `foregroundColor()` or `font()`. > > Starting from iOS 17 we can apply more intricate styling to ranges within a `Text` view with [foregroundStyle()](https://developer.apple.com/documentation/swiftui/text/foregroundstyle%28_%3A%29). > ```swift 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](https://williamyaoh.gumroad.com/l/CLyzT) > 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](https://developer.apple.com/documentation/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](https://developer.apple.com/documentation/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](https://developer.apple.com/documentation/xcode/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](https://developer.apple.com/videos/play/wwdc2023/10170) > 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](https://developer.apple.com/videos/play/wwdc2023/10166) > 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](https://developer.apple.com/videos/play/wwdc2023/10167) > 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](https://github.com/apple/swift/blob/main/lib/Macros/Sources/ObservationMacros/ObservableMacro.swift) > **Swift Observation and associated macros** * [Do LLMs eliminate the need for programming languages?](https://www.modular.com/blog/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](https://developer.apple.com/videos/play/wwdc2023/10156) > 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](https://developer.apple.com/documentation/corelocation/monitoring_location_changes_with_core_location) > Define boundaries and act on user location updates. * [Adopting live updates in Core Location](https://developer.apple.com/documentation/corelocation/adopting_live_updates_in_core_location) > Simplify location delivery using asynchronous events in Swift. * [Managing model data in your app](https://developer.apple.com/documentation/swiftui/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](https://developer.apple.com/documentation/Observation), a view in SwiftUI can form dependencies on observable data models and update the UI when data changes. * [Demystify SwiftUI performance](https://developer.apple.com/videos/play/wwdc2023/10160) > 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](https://www.figma.com/community/file/1248375255495415511) > 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](https://www.nature.com/articles/s41586-023-06004-9) > 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](https://www.deepmind.com/blog/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_](https://www.nature.com/articles/s41586-023-06004-9), 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](https://reviews.llvm.org/D118029), 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(_:)](https://developer.apple.com/documentation/SwiftUI/View/toolbarTitleDisplayMode(_:)) > Configures the toolbar title display mode for this view. * [ContentUnavailableView](https://developer.apple.com/documentation/SwiftUI/ContentUnavailableView) > An interface, consisting of a label and additional content, that you display when the content of your app is unavailable to users. * [XPCListener](https://developer.apple.com/documentation/xpc/xpclistener) > A type that performs tasks for clients across process boundaries. * [ProximityReader](https://developer.apple.com/documentation/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](https://developer.apple.com/documentation/proximityreader/setting-up-the-entitlement-for-tap-to-pay-on-iphone). * [DockKit](https://developer.apple.com/documentation/DockKit) > Interact with accessories that track subjects on camera as they move around. * [**λ Lambda Calculus Calculator λ**](https://lambdacalc.io) * [An Apple Library Primer](https://developer.apple.com/forums/thread/715385) > 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](https://developer.apple.com/documentation/Updates/wwdc2023) > Highlights of new technologies introduced at WWDC23. * [Improving build efficiency with good coding practices](https://developer.apple.com/documentation/xcode/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](https://developer.apple.com/documentation/xcode/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](https://developer.apple.com/documentation/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](https://developer.apple.com/documentation/Xcode/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](https://faultlore.com/blah/swift-abi) > 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](https://developer.apple.com/videos/play/wwdc2023/10168) > 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](https://developer.apple.com/videos/play/wwdc2023/10268) > 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](https://developer.apple.com/videos/play/wwdc2023/10226) > 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](https://developer.apple.com/documentation/xcode-release-notes/xcode-15-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](https://developer.apple.com/documentation/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](https://developer.apple.com/documentation/swiftdata/model) macro to any model class to make it persistable. Customize the behavior of that model’s properties with the [Attribute(_:renamingIdentifier:hashModifier:)](https://developer.apple.com/documentation/swiftdata/attribute(_:renamingidentifier:hashmodifier:)) and [Relationship(_:_:renamingIdentifier:inverse:hashModifier:)](https://developer.apple.com/documentation/swiftdata/relationship(_:_:renamingidentifier:inverse:hashmodifier:)) macros. Use the [ModelContext](https://developer.apple.com/documentation/swiftdata/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](https://developer.apple.com/documentation/swiftdata/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](https://developer.apple.com/documentation/SwiftUI/EnvironmentValues/modelContext) environment value, and specify a particular model container or context for a view with the [modelContainer(_:)](https://developer.apple.com/documentation/SwiftUI/View/modelContainer(_:)) and [modelContext(_:)](https://developer.apple.com/documentation/SwiftUI/View/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](https://developer.apple.com/documentation/swiftdata/schema) and [SchemaMigrationPlan](https://developer.apple.com/documentation/swiftdata/schemamigrationplan) to participate in those migrations and help them complete successfully. * [Backyard Birds: Building an app with SwiftData and widgets](https://developer.apple.com/documentation/SwiftUI/Backyard-birds-sample) > **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](https://developer.apple.com/documentation/SwiftData) for persistence, and integrates seamlessly with SwiftUI using the [Observable](https://developer.apple.com/documentation/Observation) protocol. The game’s widgets implement [App Intents](https://developer.apple.com/documentation/AppIntents) for interactive and configurable widgets. The in-app purchase experience uses the `ProductView` and `SubscriptionStoreView` from StoreKit. You can access the source code for this sample on [GitHub](https://github.com/apple/sample-backyard-birds). * [Observable](https://developer.apple.com/documentation/observation/observable-swift.macro) > **Defines and implements conformance of the Observable protocol.** * [Observation](https://developer.apple.com/documentation/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](https://developer.apple.com/documentation/observation/observable-swift.macro) macro to the type declaration. This macro declares and implements conformance to the [Observable](https://developer.apple.com/documentation/observation/observable-swift.protocol) protocol to the type at compile time. * [Applying Macros](https://developer.apple.com/documentation/swift/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](https://developer.apple.com/documentation/os/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](https://developer.apple.com/documentation/os/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](https://developer.apple.com/documentation/os/1646466-os_unfair_lock_lock) or [os_unfair_lock_unlock](https://developer.apple.com/documentation/os/1646463-os_unfair_lock_unlock) and pass a lock object using the & operator, the system may lock or unlock the wrong object. > > Instead, use [OSAllocatedUnfairLock](https://developer.apple.com/documentation/os/osallocatedunfairlock), which avoids that pitfall because it doesn’t function as a value type, despite being a structure. All copied instances of an [OSAllocatedUnfairLock](https://developer.apple.com/documentation/os/osallocatedunfairlock) control the same underlying lock allocation. * [My Approach to Building Large Technical Projects](https://mitchellh.com/writing/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](https://www.thisisartium.com/whatwethink/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](https://mjtsai.com/blog/2023/05/30/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](https://useyourloaf.com/blog/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: > > 1. Create a NWPathMonitor. > 1. Call the start method of the path monitor passing a queue that will receive path change events. > 1. Receive path changes in the pathUpdateHandler. > * [Avoiding SwiftUI’s AnyView](https://www.swiftbysundell.com/articles/avoiding-anyview-in-swiftui) > 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. > ## May * [Swift Evolution Dashboard](https://www.swift.org/swift-evolution) > 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](https://www.swift.org/community/#swift-evolution). 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](https://github.com/apple/swift-evolution) collects the goals for the upcoming major and minor releases (as defined by the [core team](https://www.swift.org/community/#core-team)) as well as proposals for changes to Swift. The [Swift evolution process](https://github.com/apple/swift-evolution/blob/main/process.md) 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](https://simon.peytonjones.org/verse-calculus) > 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. * [Using Upcoming Feature Flags](https://www.swift.org/blog/using-upcoming-feature-flags) > 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](https://forums.swift.org/t/valuesemantic-protocol/41686/59#defining-value-semantics-for-swift-1) > **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 of `a` except via an expression that uses `a`. > * Given a variable a of type `X`, safe code cannot alter the value of `a` except by one of the following means applied to `a` or to a property of `a` that reflects all or part of `a`'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](https://blog.sigplan.org/2019/12/30/defunctionalization-everybody-does-it-nobody-talks-about-it) > All told, here’s the general procedure for defunctionalization: > > 1. Collect all functions passed as an argument to the filter function. > 1. Create a data type, with one variant for each possible function, each with fields to store the free variables referenced by the corresponding function. > 1. 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](https://nilcoalescing.com/blog/TestingRemotePushOniOSSimulator) > 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](https://nilcoalescing.com/blog/AnchoredPositionInSwiftUI) > The new [Layout](https://developer.apple.com/documentation/swiftui/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()](https://developer.apple.com/documentation/swiftui/layoutsubview/place%28at%3Aanchor%3Aproposal%3A%29) method in [placeSubviews()](https://developer.apple.com/documentation/swiftui/layout/placesubviews%28in%3Aproposal%3Asubviews%3Acache%3A%29). * [`repository_dispatch`](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#repository_dispatch) > You can use the GitHub API to trigger a webhook event called [`repository_dispatch`](https://docs.github.com/en/webhooks-and-events/webhooks/webhook-events-and-payloads#repository_dispatch) when you want to trigger a workflow for activity that happens outside of GitHub. For more information, see "[Repositories](https://docs.github.com/en/rest/repos#create-a-repository-dispatch-event)." * [All about xcframeworks](https://www.humancode.us/2023/05/19/all-about-xcframeworks.html) > **An `xcframework` is a library distribution bundle** > > More 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. Each `xcframework` 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 single `xcframework` 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 an `Info.plist` file in its root. Examining its `Info.plist` file shows that it has a `CFBundlePackageType` of `XFWK`. * [Instant Pan Gesture Interactions](https://christianselig.com/2023/05/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](https://extensions.panic.com/extensions/panic/panic.Icarus) > 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!"_ * [SE: Commonly Rejected Changes](https://github.com/apple/swift-evolution/blob/main/commonly_proposed.md) > 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](https://github.com/apple/swift-evolution/blob/main/README.md) identifies a list of priorities for the next major release of Swift, and the [dashboard](https://www.swift.org/swift-evolution) 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 in `if` statements). * [Swift memory usage](https://forums.swift.org/t/swift-memory-usage/64943/6) > I agree it's not very _relevant_ in this case, but I have measured this :slightly_smiling_face: 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` and `int` > * 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](https://www.donnywals.com/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](https://medium.com/airbnb-engineering/flexible-continuous-integration-for-ios-4ab33ea4072f) > 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](https://bendodson.com/weblog/2023/05/10/connecting-a-tvos-app-to-ios-ipados-and-watchos-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](https://swiftfiddle.com) > 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](https://www.swiftbysundell.com/articles/retrying-an-async-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! > ```swift 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](https://github.com/pointfreeco/swift-validated) > A result type that accumulates multiple errors. * [Mojo Dojo](https://mojodojo.dev) > Learning Resources for Mojo 🔥 * [Using Swift’s Types as Domain-Specific Languages](https://medium.com/codex/using-swifts-types-as-domain-specific-languages-6f03b90fe218) > 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:](https://octodon.social/@torb/110326664167081742) > > * Sketch > * PaintCode > * DetailsPro > * Drama > * Principle > * Origami Studio > * Judo > * Kolibri > * Flinto > * OmniGraffle > * Keynote > * Tumult Hype > * Play > * [The Ultimate Domain Language: Declarative Swift](https://betterprogramming.pub/the-ultimate-domain-language-declarative-swift-37b0a04e4e32) > Exploring declarative domain paradigm * [HIG Layout](https://developer.apple.com/design/human-interface-guidelines/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](https://developer.apple.com/documentation/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](https://developer.apple.com/documentation/swiftui/layout-adjustments). To define custom layout containers, see [Custom layout](https://developer.apple.com/documentation/swiftui/custom-layout). For design guidance, see [Layout](https://developer.apple.com/design/human-interface-guidelines/foundations/layout) in the Human Interface Guidelines. * [overlay(alignment:content:)](https://developer.apple.com/documentation/swiftui/view/overlay(alignment:content:)) > Layers the views that you specify in front of this view. * [The power of overlays in SwiftUI](https://swiftwithmajid.com/2023/05/03/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](https://contextsdk.com) > 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](https://byrdhouseapp.com) > 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](https://docs.modular.com/mojo/programming-manual.html) > 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](https://en.wikipedia.org/wiki/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.](https://www.modular.com/mojo) > 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](https://performance.modular.com) > The Performance Dashboard is where you can compare the performance of standard industry models on Modular’s infrastructure. * [Supporting passkeys](https://developer.apple.com/documentation/authenticationservices/public-private_key_authentication/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](https://www.apple.com/newsroom/2023/05/apple-google-partner-on-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](https://developer.apple.com/documentation/docc) > Produce rich API reference documentation and interactive tutorials for your app, framework, or package. * [DocC API Documentation](https://developer.apple.com/documentation/docc/api-reference-syntax) > 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](https://developer.apple.com/documentation/docc/tutorial-syntax) > Teach developers your Swift and Objective-C APIs through step-by-step, interactive content. * [Platform as a Product](https://tomgeraghty.co.uk/index.php/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. > ## April * [UIViewController.ViewLoading](https://developer.apple.com/documentation/uikit/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 as [`Optional`](https://developer.apple.com/documentation/swift/optional), and then referencing them before the view controller finishes loading. * [SCRAPSCRIPT](https://scrapscript.org) > 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](https://riskstorming.com) > > 1. Draw some software architecture diagrams > 1. Identify the risks individually > 1. Converge the risks on the diagrams > 1. Review and summarise the risks > * [**Architecture Modernization [Miro]**](https://miro.com/app/board/uXjVPCh97B0=/) * [openAI Unison Share](https://share.unison-lang.org/@runarorama/p/code/latest/namespaces/public/openai) * [The Hackett Programming Language](https://lexi-lambda.github.io/hackett) > _Hackett_ is a statically typed, pure, lazy, functional programming language in the Racket language ecosystem. Despite significant differences from [#lang](http://docs.racket-lang.org/guide/Module_Syntax.html#%28part._hash-lang%29) [racket](http://docs.racket-lang.org/reference/index.html), 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](https://www.danijelavrzan.com/posts/2023/04/login-xcode-breakpoint) > 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](https://developer.apple.com/documentation/swift/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 the `Set` type with elements of any hashable type, or you can easily create bit masks with `SetAlgebra` conformance using the `OptionSet` protocol. See those types for more information. * [Byte Code Based Value Witnesses](https://forums.swift.org/t/sr-14273-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**](https://jvns.ca/blog/2023/04/17/a-list-of-programming-playgrounds) * [Reimagining the microservice: an early preview](https://www.unison-lang.org/whats-new/unison-services-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](https://developer.apple.com/documentation/xcode/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**](https://swift-ast-explorer.com) * [Compose Multiplatform](https://www.jetbrains.com/lp/compose-multiplatform) > Develop stunning shared UIs for Android, iOS, desktop, and web. * [Allow Generic Types to Abstract Over Packs](https://forums.swift.org/t/pitch-variadic-generic-types-abstracting-over-packs/64377) > 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 in `let seq` and `var iter` above. * [**Shortcuts File Format Documentation**](https://zachary7829.github.io/blog/shortcuts/fileformat) * [**Deep Into Shortcuts**](https://zachary7829.github.io/blog/shortcuts) * [Observation](https://github.com/apple/swift-evolution/blob/main/proposals/0395-observability.md) > 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](https://developer.apple.com/documentation/swiftui/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](https://developer.apple.com/documentation/swiftui/scrollview), and switch to lazy stacks as performance issues arise. * [Height](https://height.app) > **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](https://tomasp.net/techdims) > 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](https://www.pathsensitive.com/2023/03/modules-matter-most-for-masses.html) > 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](https://www.pathsensitive.com/2021/03/why-programmers-shouldnt-learn-theory.html) > 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](https://www.tramline.app) > _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** ```swift let neverJSON = Data(#"{"no":"never"}"#.utf8) ``` * [Deque](https://github.com/apple/swift-collections/blob/main/Documentation/Deque.md) > A collection implementing a double-ended queue. * [**CaseDetectionMacro.swift**](https://github.com/DougGregor/swift-macro-examples/blob/main/MacroExamplesPlugin/CaseDetectionMacro.swift) * [**swift-macro-examples**](https://github.com/DougGregor/swift-macro-examples/blob/main/MacroExamples/main.swift) * [Imperative Programming with Poly](https://topos.site/blog/2023/04/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](https://chris.eidhof.nl/post/matched-geometry-effect) > `The Declaration Order Matters` * [How to Set Up an Edit-Build-Test-Debug Loop](https://github.com/apple/swift/blob/main/docs/HowToGuides/GettingStarted.md#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](https://github.com/apple/swift/tree/main/tools/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](https://developer.apple.com/documentation/distributed/localtestingdistributedactorsystem) > A `DistributedActorSystem` designed for local only testing. * [How to be a -10x Engineer](https://taylor.town/-10x) > **+10x engineers may be mythical, but -10x engineers exist.** > > **To become a -10x engineer, simply waste 400 engineering hours per week.** * [higher-free-macro](https://crates.io/crates/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. > ## March * [The Streaming Book](https://www.thestreamingbook.com) > 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?](https://github.com/pointfreeco/swift-composable-architecture/blob/main/Tests/ComposableArchitectureTests/SerialExecutor.swift#L1-L12) > 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](https://github.com/apple/swift-async-algorithms), in particular, a "[C async support](https://github.com/apple/swift-async-algorithms/tree/main/Sources/_CAsyncSequenceValidationSupport)" module, which exposes [a global hook override](https://github.com/apple/swift-async-algorithms/blob/e6b21d2a6d6cf8c886a97fba489563fd885937d4/Sources/_CAsyncSequenceValidationSupport/_CAsyncSequenceValidationSupport.h#L246) for task enqueuing, which we use to redirect everything to the main, serial executor: > ```swift 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](https://nilcoalescing.com/blog/ForegroundColorStyleAndTintInSwiftUI) > SwiftUI has a few different modifiers that can change the color of text, such as [foregroundColor(_:)](https://developer.apple.com/documentation/swiftui/view/foregroundcolor%28_%3A%29), [foregroundStyle(_:)](https://developer.apple.com/documentation/swiftui/view/foregroundstyle%28_%3A%29), and [tint(_:)](https://developer.apple.com/documentation/swiftui/view/tint%28_%3A%29-93mfq). 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](https://oleb.net/2023/swiftui-relative-size-in-stacks) > _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](https://oleb.net/2023/swiftui-relative-size). 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](https://github.com/tramlinehq/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](https://marcelvoss.com/2023/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](https://oleb.net/2023/swiftui-relative-size) > 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](https://developer.apple.com/documentation/avfoundation/avmetadataobject/objecttype) * Constants that identify metadata object types. * [Verse Language Reference](https://dev.epicgames.com/documentation/en-us/uefn/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](https://dev.epicgames.com/documentation/en-us/uefn/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](https://acropalypse.app) > Screenshot recovery utility * [Migrating to new navigation types](https://developer.apple.com/documentation/swiftui/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](https://developer.apple.com/documentation/swiftui/navigationview). In its place, use [NavigationStack](https://developer.apple.com/documentation/swiftui/navigationstack) and [NavigationSplitView](https://developer.apple.com/documentation/swiftui/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](https://developer.apple.com/documentation/xctest/xctcontext) > _A proxy for the current testing context._ > > `XCTContext` provides a way for activities ([XCTActivity](https://developer.apple.com/documentation/xctest/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:)](https://developer.apple.com/documentation/xctest/xctcontext/2923506-runactivity) to run a block of code as a named substep in a test. For more information, see [Grouping Tests into Substeps with Activities](https://developer.apple.com/documentation/xctest/activities_and_attachments/grouping_tests_into_substeps_with_activities). * [Grouping Tests into Substeps with Activities](https://developer.apple.com/documentation/xctest/activities_and_attachments/grouping_tests_into_substeps_with_activities) > Simplify test reports by creating activities that organize substeps within complex test methods. * [On trust in software development](https://blog.ploeh.dk/2023/03/20/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](https://betterprogramming.pub/using-swifts-type-system-to-model-behaviour-2a1ba566b776) > Create fully immutable types for your domain using Swift * [Spelunking Apple’s Open Source](https://bitsplitting.org/2023/03/17/spelunking-apples-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](https://www.magnuskahr.dk/posts/2023/03/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. > ```swift 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](https://www.sciencedirect.com/science/article/pii/S0164121222002485) > 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. * [VNDetectBarcodesRequest](https://developer.apple.com/documentation/vision/vndetectbarcodesrequest) > A request that detects barcodes in an image. * [The First ACM SIGPLAN Workshop on Functional Software Architecture — FP in the Large](https://www.functional-architecture.org/events/funarch-2023/cfp) > “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](https://degoes.net/articles/fp-glossary) > 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 in Swift](https://medium.com/swift-coding/tries-in-swift-4afb9b82785f) > 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**](https://www.evilsocket.net/2022/10/20/Reverse-Engineering-the-Apple-MultiPeer-Connectivity-Framework) * [Building Large-Scale Apps with SwiftUI: A Guide to Modular Architecture](http://azamsharp.com/2023/02/28/building-large-scale-apps-swiftui.html) > 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](https://azamsharp.com/2022/10/06/practical-mv-pattern-crud.html). In this article, I will discuss how MV pattern can be applied to build large scale client/server applications. * [Unlisted app distribution](https://developer.apple.com/support/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. > * [Pitch: Dependent Types & Universes](https://forums.swift.org/t/dependent-types-universes/63754) > 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. * [Petey - Al Assistant](https://apps.apple.com/us/app/petey-ai-assistant/id6446047813) > 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. * [CodableWithConfiguration](https://developer.apple.com/documentation/foundation/codablewithconfiguration) > _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](https://developer.apple.com/documentation/foundation/encodablewithconfiguration) and [DecodableWithConfiguration](https://developer.apple.com/documentation/foundation/decodablewithconfiguration) protocols. Use this protocol to support codability in a type that can’t conform to [Codable](https://developer.apple.com/documentation/swift/codable) by itself, but can do so with additional statically-defined configuration provided by a [CodableConfiguration](https://developer.apple.com/documentation/foundation/codableconfiguration) instance. > > [AttributedString](https://developer.apple.com/documentation/foundation/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](https://developer.apple.com/documentation/foundation/attributescope) instances, a type that conforms to [EncodingConfigurationProviding](https://developer.apple.com/documentation/foundation/encodingconfigurationproviding) and [DecodingConfigurationProviding](https://developer.apple.com/documentation/foundation/decodingconfigurationproviding). An attribute scope like [AttributeScopes.SwiftUIAttributes](https://developer.apple.com/documentation/foundation/attributescopes/swiftuiattributes) defines attribute keys, and conforms to `AttributeScope` to provide configuration instances that know the [AttributedStringKey](https://developer.apple.com/documentation/foundation/attributedstringkey) types and their associated [Value](https://developer.apple.com/documentation/foundation/attributedstringkey/3765878-value) types. With this type information, an `AttributedString` can encode all of its attributes, even from frameworks other than Foundation. * [**π**](https://github.com/π) * [Compiling Swift generics, Part I](https://forums.swift.org/t/compiling-swift-generics-part-i/60898) > The target audience is Swift compiler developers: if you've previously encountered `GenericSignatures`, `GenericEnvironments`, `SubstitutionMaps` and `ProtocolConformances` 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. * [Monads as lax functors](https://www.paolocapriotti.com/blog/2015/06/22/monads-as-lax-functors/index.html) > _A monad is a lax 2-functor from the terminal 2-category 1 to_ **Cat**. * [TypeScript magic](https://artsy.github.io/blog/2023/03/01/typescript-magic) > `const wow: ("hello" | "world") | (string & {})` // `wow` is of type `"hello"` or `"world"` or `string`. > > This weird-looking intersection of `string & {}` makes it so that the specific strings `"hello"` and `"world"` are distinguished from `string` as a whole type. * [How to Change the Background Color of Navigation Bars in all iOS versions?](https://holyswift.app/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](https://share.unison-lang.org/@rlmark/p/code/latest/namespaces/public/projects/visualizeRemote) > This project contains a version of [Remote.pure.run](https://share.unison-lang.org/@rlmark/p/code/latest/namespaces/public/projects/visualizeRemote/;/terms/@368phg51vntlrseja3vc7f12eicg9ir54cd1loi8fingufttii7fefpj1lj8ibrj19dc441orlh53ma54dgr6v0rhgd1rku9sr0vhio) that is capable of programmatically producing [mermaid diagrams](https://mermaid.js.org) to visualize the forked and awaited tasks in a [Remote](https://share.unison-lang.org/@rlmark/p/code/latest/namespaces/public/projects/visualizeRemote/;/types/@2vmrc5ruttsh3hsh6u7e5vksai8uvaa9657ur3aa6dj8rrmpgc89o166fadhslk4kiijosmjgel27sa37hamesvcolqefmiia41mtdo) computation. * [En dash, em dash and hyphen; what’s the difference? (also ndash and mdash, or n-dash and m-dash)](https://www.punctuationmatters.com/en-dash-em-dash-hyphen) > 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! * [IndieWebify.Me](https://indiewebify.me) > **A guide to getting you on the [IndieWeb](https://indieweb.org)** > > * Become a citizen of the IndieWeb > * Publishing on the IndieWeb > * Federating IndieWeb Conversations > * [9 PROCESSING PATTERNS](https://www.messagehandler.net/patterns) > 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.](https://forums.swift.org/t/why-cant-i-cast-woo-any-to-woo-int-concrete-type-but-array-any-to-array-int-is-ok/63556/15) > 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[]` to `Object[]`, but assignments into the result will fail with an exception if they aren't dynamically `String`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](https://frankrausch.com/ios-navigation) > 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](https://developer.apple.com/design/human-interface-guidelines), written by [someone](https://frankrausch.com) who cares deeply about well-crafted user interfaces. * [Introducing Swift Certificates and Swift ASN.1](https://www.swift.org/blog/swift-certificates-and-asn1) > I’m excited to announce two new open source Swift packages: [swift-certificates](https://github.com/apple/swift-certificates) and [swift-asn1](https://github.com/apple/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. * [JiraPT-3](https://www.jirapt3.com) > **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](https://blocks.githubnext.com) > 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](https://developer.apple.com/documentation/xcode/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. * [AsyncGraphics](http://async.graphics/documentation/AsyncGraphics) > _Edit images and video with async / await in Swift, powered by Metal._ > > The main value type in **AsyncGraphics** is a [Graphic](http://async.graphics/documentation/asyncgraphics/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](http://async.graphics/documentation/asyncgraphics/graphic3d). It’s a 3d image, a volume of voxels. > > [AsyncGraphics on GitHub](https://github.com/heestand-xyz/AsyncGraphics) * [HIG Writing](https://developer.apple.com/design/human-interface-guidelines/foundations/writing) > 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. * [Why be pure?](https://rachel.cafe/2022/12/10/why-be-pure.html) > 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](https://www.swiftbysundell.com/articles/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](https://developer.apple.com/documentation/xcode/organizing-tests-to-improve-feedback) > 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](https://www.judo.app) > 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](https://www.jessesquires.com/blog/2023/03/02/icloud-tabs-bug) > > 1. On your Mac, backup your Safari data — bookmarks, etc. Just in case. > 1. Completely quit Safari on all devices. > 1. 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. > 1. Launch Safari on all devices. Bookmarks, etc. should be gone on iOS. > 1. Completely quit Safari on all devices, again. > 1. Reboot all devices. > 1. Re-enable Safari syncing in iCloud settings on all devices. > 1. Launch Safari on your Mac, so it can sync the initial data. > 1. Launch Safari on all iOS devices. > * [SwiftUI: The difference between List and LazyVStack](https://dimillian.medium.com/swiftui-the-difference-between-list-and-lazyvstack-3d5eeaccb156) > 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! * [You Don't Need Routes](https://chris.eidhof.nl/post/simpler-swift-apis) > 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. * [Never use git submodules](https://diziet.dreamwidth.org/14666.html) > 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](https://manpages.debian.org/stable/git-man/git-subtree.1.en.html) solves many of the same problems as git submodule, but it does not violate the git data model. * [StateObject](https://developer.apple.com/documentation/swiftui/stateobject) > 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](https://developer.apple.com/documentation/swiftui/app), [Scene](https://developer.apple.com/documentation/swiftui/scene), or [View](https://developer.apple.com/documentation/swiftui/view) by applying the `@StateObject` attribute to a property declaration and providing an initial value that conforms to the [ObservableObject](https://developer.apple.com/documentation/Combine/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](https://developer.apple.com/documentation/swiftui/text) view in the above example. > > **_Note_: If you need to store a value type, like a structure, string, or integer, use the [State](https://developer.apple.com/documentation/swiftui/state) property wrapper instead.** * [Lightweight Formal Methods: String Diagrams](https://flexport.engineering/lightweight-formal-methods-string-diagrams-ac44249ca2cd) > 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](https://www.unison-lang.org/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. > ## February * [Resolving architecture build errors on Apple silicon](https://developer.apple.com/documentation/technotes/tn3117-resolving-build-errors-for-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](https://oleb.net/blog/2023/catch-error-code) > **tl;dr** Foundation overloads the pattern matching operator `~=` to enable matching against error codes in `catch` clauses. * [Implicitly Opened Existentials](https://github.com/apple/swift-evolution/blob/main/proposals/0352-implicit-open-existentials.md) > 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(\_:)](https://developer.apple.com/documentation/swiftui/viewbuilder/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](https://apps.apple.com/us/app/reeder-5/id1529448980) > 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](https://gist.github.com/Hirrolot/27e6b02a051df333811a23b97c375196) > 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, and `zip` 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](https://twitter.com/dgregor79/status/850554785396740097) > > 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](https://www.linkedin.com/pulse/how-remove-git-commit-history-nitin-raturi) > > * 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](https://reactjs.org/docs/error-boundaries.html) > In the past, JavaScript errors inside components used to corrupt React’s internal state and cause it to [emit](https://github.com/facebook/react/issues/4026) [cryptic](https://github.com/facebook/react/issues/6895) [errors](https://github.com/facebook/react/issues/8579) 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](https://github.com/pointfreeco/swift-case-paths/pull/101) > 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. > ```swift try XCTModify(&result, case: /Result.success) { $0 += 1 } ``` * [Xcode tip: sharing breakpoints across projects](https://www.jessesquires.com/blog/2023/02/21/xcode-tip-sharing-breakpoints) > 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](https://medium.com/@abdelrahman_adm/shake-gesture-in-swiftui-1ce0342fbb4e) > 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 for `UIWindow`, and override `motionEnded` method. > ```swift extension UIWindow { override func motionEnded(_ motion: UIEvent.EventSubtype, with: UIEvent?) { guard motion = .motionShake else { return } NotificationCenter.default.post(name: UIDevice.deviceDidShake, object: nil) } } ``` * [Base](https://base.org) > 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?](https://forums.swift.org/t/reliably-testing-code-that-adopts-swift-concurrency/57304/29) ```swift 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**](https://github.com/isovector/composition/blob/master/prose/intro.md) > > 1. Decompose the problem into its constituent mental pieces > 1. Solve the problem there > 1. Mentally compile the solution into software > * [Learn HTML](https://web.dev/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](https://developer.apple.com/documentation/xcode/installing-additional-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](https://developer.apple.com/documentation/MultipeerConnectivity) > 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](https://forums.swift.org/t/struct-and-enum-accessors-take-a-large-amount-of-stack-space/63251/12) > 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: ```swift 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](https://developer.apple.com/documentation/swiftui/toolbartitlemenu) > The title menu of a toolbar. * [The Art of Sequential Animations in SwiftUI: Tips, Tricks, and Examples](https://holyswift.app/how-to-do-sequential-animations-in-swiftui) > 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](https://xcode.tips/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!](https://mobile.twitter.com/SwiftyAlex/status/1626989662353891328) > 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](https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/DynamicLibraryUsageGuidelines.html) > 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](https://apps.apple.com/app/id1659984546) > 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](https://docs.swift.org/swift-book/documentation/the-swift-programming-language) > Understand the high-level goals of the language. * [WebURL Key-Value Pairs](https://gist.github.com/karwa/bb8eb387dac10fd7c0c1fffc020c1c7c#proposed-solution) > 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](https://holyswift.app/how-to-do-sequential-animations-in-swiftui) > 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?](https://ishtiz.com/swift/what-is-copy-on-writecow-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](https://ishtiz.com/swift/value-and-reference-types-in-swift-a-deep-dive) type. * [The Change of Mobile Teams Topology for an Organization](https://medium.com/mobile-app-development-publication/the-change-of-mobile-teams-topology-for-an-organization-d6fb1f6ff75b) > Optimize the structure of mobile teams to fit the need of the organization in scaling app development. * [iOS and iPadOS usage](https://developer.apple.com/support/app-store) > As measured by devices that transacted on the App Store. * [Composable Styles in SwiftUI](https://movingparts.io/composable-styles-in-swiftui) > A look at how to compose styles and how to make custom views support composable styles. * [pointfreeco/swift-clocks](https://github.com/pointfreeco/swift-clocks) > ⏰ A few clocks that make working with Swift concurrency more testable and more versatile. * [Creating an XCFramework](https://rhonabwy.com/2023/02/10/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](https://developer.apple.com/documentation/xcode/creating-a-multi-platform-binary-framework-bundle): > > 1. 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. > 1. 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. > 1. 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. > 1. 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. > 1. 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 * [A Beginner’s Guide to Styling Components in SwiftUI](https://holyswift.app/a-beginners-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](https://www.genius.design) > It understands what you’re designing and makes suggestions that autocomplete your design using components from your design system. * [**Developer Conferences Agenda**](https://developers.events) * [Managing a merge queue](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/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](https://docs.github.com/en/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 the `base_branch` as well as changes ahead of it in the queue. GitHub will merge all these changes into `base_branch` once the checks required by the branch protections of `base_branch` pass. * [Adding a stretchable header to a SwiftUI ScrollView](https://danielsaidi.com/blog/2023/02/06/adding-a-stretchable-header-to-a-swiftui-scroll-view) > 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](https://github.com/danielsaidi/ScrollKit) library. You can find the source code [here](https://github.com/danielsaidi/ScrollKit/blob/main/Sources/ScrollKit/ScrollViewHeader.swift). If you decide to give it a try, I’d be very interested in hearing what you think. * [Styling Components in SwiftUI](https://movingparts.io/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](https://www.polpiella.dev/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](https://support.apple.com/en-us/HT201412) > 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) > 1. Press and quickly release the volume up button. > 1. Press and quickly release the volume down button. > 1. Press and hold the side button until you see the Apple logo. * [[Pitch] Type Wrappers](https://forums.swift.org/t/pitch-type-wrappers/60019/45) > I've been working on the implementation for [attached macros](https://forums.swift.org/t/pitch-attached-macros/62812), and I had the chance to implement [@Observable](https://github.com/DougGregor/swift-macro-examples/pull/6) from the Future Directions section of the [observation pitch](https://forums.swift.org/t/pitch-observation/62051). 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 an `actor`). > > 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](https://github.com/Asperi-Demo/4SwiftUI/blob/master/PlayOn_iOS/PlayOn_iOS/Findings/TestTextEditorToFocus.swift) ```swift 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](https://zhuk.fi/subclassing-urlcache) > 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](https://swdevnotes.com/swift/2023/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](https://www.vadimbulavin.com/how-to-move-swiftui-view-when-keyboard-covers-text-field) > 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**](https://forums.swift.org/t/structures-and-classes-quick-reference-guide/62889) >  * [**Lenses, Transducers, and Algebraic Effects**](https://ikrima.dev/dev-notes/prog-lang-theory/plt-lenses-transducers-effects) * [Understanding transducers](https://andreyorst.gitlab.io/posts/2022-08-13-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. > ## January * [Styling Components in SwiftUI](https://movingparts.io/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](https://pml.flu.cas.cz) > 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](https://apps.apple.com/us/app/ice-cubes-for-mastodon/id6444915884) > Ice Cubes is a fast, reliable and beautiful Mastodon client. * [ClimateTechList.com](https://www.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”](https://blog.timing.is/swiftui-production-experience-problems-solutions-performance-tips) > 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](https://azamsharp.com/2023/01/24/introduction-to-container-pattern.html) > 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?](https://marcpalmer.net/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 with `scrollTo(id:,anchor:)` — in my case I map my model data to an array of new enum types that describe what the `ForEach` should output for each iteration. * [Using complex gestures in a SwiftUI ScrollView](https://danielsaidi.com/blog/2022/11/16/using-complex-gestures-in-a-scroll-view) > 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](https://azamsharp.com/2012/12/23/pragmatic-unit-testing.html) > 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**](https://www.pointfree.co/live) * [How to setup CloudKit subscription to get notified for changes](https://nemecek.be/blog/31/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](https://racecondition.software/blog/swiftui-homeworks) > In a [recent post](https://racecondition.software/blog/challenges), 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](https://github.com/vermont42/CatFancy) 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](https://douglashill.co/javascript-in-swift) > 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](https://www.youtube.com/watch?v=Cp5_o2lDqj0) > [](https://www.youtube.com/watch?v=Cp5_o2lDqj0) * [SwiftUI under the Hood: Variadic Views](https://movingparts.io/variadic-views-in-swiftui) > 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](https://github.com/roc-lang/roc/blob/main/roc-for-elm-programmers.md) > 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](https://chris.eidhof.nl/post/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](http://movingparts.io/variadic-views-in-swiftui) 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](https://testableapple.com/note-37) > 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](https://blog.eidinger.info/save-money-when-using-github-actions-for-ios-cicd) > 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](https://samwize.com/2023/01/18/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](https://chris.eidhof.nl/post/swiftui-state-lifetime) > _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](https://chris.eidhof.nl/post/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](https://betterprogramming.pub/environment-values-as-an-alternative-to-dependency-injection-in-swiftui-a9de89854afe) > Using Environment Values to avoid unnecessary body re-evaluations and make our views more self-contained. * [The Nested Observables Problem in SwiftUI](https://holyswift.app/how-to-solve-observable-object-problem) > 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](https://www.swiftbysundell.com/articles/accessing-a-swift-property-wrappers-enclosing-instance) > However, if we take a look at the [Swift Evolution proposal](https://github.com/apple/swift-evolution/blob/master/proposals/0258-property-wrappers.md#referencing-the-enclosing-self-in-a-wrapper-type) 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](https://github.com/apple/swift/blob/c8f4b09809de1fab3301c0cfc483986aa6bdecfa/stdlib/public/core/Misc.swift#L87-L94) > Returns the demangled qualified name of a metatype. * [func _typeByName(_ name: String) -> Any.Type?](https://github.com/apple/swift/blob/c8f4b09809de1fab3301c0cfc483986aa6bdecfa/stdlib/public/core/Misc.swift#L118-L127) > 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](https://www.emergetools.com/blog/posts/how-order-files-speed-up-protocols) > 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](https://docs.emergetools.com/docs/launch-booster-ios#using-the-file) 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](https://github.com/kodecocodes/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](https://aquarchitect.github.io/swift-algorithm-club). * [Data Laced with History: Causal Trees & Operational CRDTs](http://archagon.net/blog/2018/03/24/data-laced-with-history) > 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](https://developer.apple.com/documentation/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](https://engineering.mercari.com/en/blog/entry/20211129-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](https://einarwh.wordpress.com/2020/04/05/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](https://github.com/apple/swift/issues/62978#issuecomment-1381099547) > 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 of `buildPartialBlock` 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 without `buildExpression` or `buildPartialBlock` providing more context (via generic requirements) just like if you wrote `_ = Int.parser()` without using result builders. * [Caching network data](https://developer.apple.com/tutorials/app-dev-training/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](https://www.pointfree.co/blog/posts/78-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 as `NavigationStack`, which helps decouple domains in a navigation stack while simultaneously retaining type information to pass to destination views. * [NavPath.swift](https://gist.github.com/mbrandonw/ed5d14b86e263fa6df008329cba74142) > Reverse engineering SwiftUI's NavigationPath * [Transferable](https://developer.apple.com/documentation/coretransferable/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](https://developer.apple.com/documentation/photokit/bringing_photos_picker_to_your_swiftui_app) > Select media assets by using a Photos picker view that SwiftUI provides. * [Image Caching with URLCache](https://levelup.gitconnected.com/image-caching-with-urlcache-4eca5afb543a) > 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](https://forums.swift.org/t/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](https://forums.swift.org/t/manifesto-ownership/5212)), 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](https://developer.apple.com/documentation/foundation/url_loading_system/accessing_cached_data) > Control how URL requests make use of previously cached data. * [Google Nearby Connections API](https://developers.google.com/nearby/connections/overview) > 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](https://cocoaphony.micro.blog/2022/10/29/solving-required-kernel.html) > 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](https://developer.apple.com/documentation/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!](https://www.areweserveryet.org) > Swift has a mature and production ready framework in [Vapor](https://www.vapor.codes) and [Smoke](https://github.com/amzn/smoke-framework), and newer ones like [Hummingbird](https://github.com/hummingbird-project/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](https://developer.apple.com/documentation/swiftui/asyncimage) > A view that asynchronously loads and displays an image. * [withCheckedThrowingContinuation(function:_:)](https://developer.apple.com/documentation/swift/withcheckedthrowingcontinuation(function:_:)) > Suspends the current task, then calls the given closure with a checked throwing continuation for the current task. * [CRAFTING INTERPRETERS](https://craftinginterpreters.com) > _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](https://developer.apple.com/documentation/cloudkit/shared_records/sharing_cloudkit_data_with_other_icloud_users) > Create and share private CloudKit data with other users by implementing the sharing UI. * [CloudKit Shared Records](https://developer.apple.com/documentation/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](https://blog.justtact.com/advanced-data-protection) > 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](https://developer.apple.com/documentation/cloudkit/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](https://developer.apple.com/documentation/cloudkit/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:_:)](https://developer.apple.com/documentation/swiftui/view/task(priority:_:)) > Adds an asynchronous task to perform before this view appears. * [task(id:priority:\_:)](https://developer.apple.com/documentation/swiftui/defaultsharelinklabel/task(id:priority:_:)) > Adds a task to perform before this view appears or when a specified value changes. * [Using cktool](https://developer.apple.com/icloud/ck-tool) > `cktool` is stateless and passes all operations to the CloudKit Management API in single operations. * [Clarification needed on UnsafeContinuation documentation](https://forums.swift.org/t/clarification-needed-on-unsafecontinuation-documentation/57803) > 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](https://support.apple.com/en-us/HT212654) > Learn what to do if you can’t set up or update your HomePod after Advanced Data Protection is enabled. * [CurrentValueSubject](https://developer.apple.com/documentation/combine/currentvaluesubject) > A subject that wraps a single value and publishes a new element whenever the value changes. > > Unlike [PassthroughSubject](https://developer.apple.com/documentation/combine/passthroughsubject), [CurrentValueSubject](https://developer.apple.com/documentation/combine/currentvaluesubject) maintains a buffer of the most recently published element. * [Freestanding Macros](https://github.com/DougGregor/swift-evolution/blob/freestanding-macros/proposals/nnnn-freestanding-macros.md#freestanding-macros) > [SE-0382 "Expression macros"](https://github.com/apple/swift-evolution/blob/main/proposals/0382-expression-macros.md) 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. * [Attached Macros](https://github.com/DougGregor/swift-evolution/blob/attached-macros/proposals/nnnn-attached-macros.md) > 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](https://blocks.githubnext.com) > Extend your codebase with custom, interactive blocks. > > Build rich documentation, enhance your workflows, and bring your repository to life. * [The latest GitHub previews ✨](https://github.com/features/preview) > Be the first to try out GitHub’s new features * [Truncating git history](https://passingcuriosity.com/2017/truncating-git-history) ```bash git checkout --orphan temp e41d7f633c45c46bd42e97cecf93204191d9e4c9 git commit -m "Truncate history" git rebase --onto temp e41d7f633c45c46bd42e97cecf93204191d9e4c9 master ``` * [ImageRenderer](https://developer.apple.com/documentation/swiftui/imagerenderer) > An object that creates images from SwiftUI views. * [How task locals work](https://pointfreeco.github.io/swift-dependencies/main/documentation/dependencies/lifetimes) > 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](https://gist.github.com/tkersey/b06986c421ae19dbff089a022afba78c) ```swift 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](https://github.com/vapor-community/HTMLKit) > Create and render HTML templates with HTMLKit. * [Writing Haskell with Chat GPT](https://mmhaskell.com/blog/2023/1/16/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](https://developer.apple.com/documentation/swift/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 or `async let` created tasks). * [ActorIsolated](https://pointfreeco.github.io/swift-dependencies/main/documentation/dependencies/actorisolated) > A generic wrapper for isolating a mutable value to an actor. * [LockIsolated](https://pointfreeco.github.io/swift-dependencies/main/documentation/dependencies/lockisolated) > A generic wrapper for isolating a mutable value with a lock. * [CKUserIdentity](https://developer.apple.com/documentation/cloudkit/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:)](https://developer.apple.com/documentation/cloudkit/ckcontainer/1399174-requestapplicationpermission). * [Neovim's Terminal Emulator](https://thoughtbot.com/upcase/videos/neovims-terminal-emulator) > In Neovim, we can launch a terminal emulator by running the `:terminal` command. * [BindableState](https://pointfreeco.github.io/swift-composable-architecture/main/documentation/composablearchitecture/bindablestate) > A property wrapper type that can designate properties of app state that can be directly bindable in SwiftUI views. * [BindableAction](https://pointfreeco.github.io/swift-composable-architecture/main/documentation/composablearchitecture/bindableaction) > An action type that exposes a `binding` case that holds a [BindingAction](https://pointfreeco.github.io/swift-composable-architecture/main/documentation/composablearchitecture/bindingaction). * [BindingReducer](https://pointfreeco.github.io/swift-composable-architecture/main/documentation/composablearchitecture/bindingreducer) > A `reducer` that updates bindable state when it receives binding actions. * [TCA Working with SwiftUI bindings](https://pointfreeco.github.io/swift-composable-architecture/main/documentation/composablearchitecture/bindings) > Learn how to connect features written in the Composable Architecture to SwiftUI bindings. * [TCA Store](https://pointfreeco.github.io/swift-composable-architecture/main/documentation/composablearchitecture/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](https://swiftpackageindex.com/omaralbeik/Stores/main/documentation/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](https://www.unison-lang.org/learn/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](https://share.unison-lang.org/@alvaroc1/p/code/latest/namespaces/public/mermaid/main) > Draw charts renderable using mermaid-js. Only sequence diagrams supported at the moment. * [Unison — Html](https://share.unison-lang.org/@hojberg/p/code/latest/namespaces/public/projects/html/latest) > This is a small Html combinator library for building up an Html document. The API is 's heavily inspired by the [Elm Html library](https://github.com/elm/html). * [Making Haskell lenses less pointless](https://julesh.com/2023/01/14/making-haskell-lenses-less-pointless) > `type Value f s t r = (s -> f t) -> f r` * [Mac OS X and PDF](https://www.prepressure.com/pdf/basics/osx-quartz) > 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](https://tratt.net/laurie/blog/2023/compiled_and_interpreted_languages_two_ways_of_saying_tomato.html) > 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](https://oleb.net/2022/swiftui-view-lifecycle) > 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 a `onFirstAppear` helper, as shown by Ian Keen and Jordan Morgan in [Running Code Only Once in SwiftUI (2022-11-01)](https://www.swiftjectivec.com/swiftui-run-code-only-once-versus-onappear-or-task). * [Low-level Swift optimization tips](https://swiftinit.org/articles/low-level-swift-optimization) > 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](https://www.polpiella.dev/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 latest `main` revision of the [swift-aws-lambda-runtime package](https://github.com/swift-server/swift-aws-lambda-runtime) and take an early look at what the new APIs look like and how they enable us to use `async/await` in AWS lambdas. * [Text modifiers in SwiftUI](https://nilcoalescing.com/blog/TextModifiersInSwiftUI) > Apart from regular view modifiers in SwiftUI, there are also text modifiers. They apply specific styles to a `Text` view and return another `Text` rather than `some View`. We can see the list of available text modifiers in the [Text view documentation](https://developer.apple.com/documentation/swiftui/text) under the "Styling the view’s text" and other sections. These are the ones that have `Text` as their return type, for example `func foregroundColor(Color?) -> Text`. * [Text](https://developer.apple.com/documentation/swiftui/text) > A view that displays one or more lines of read-only text. * [Swift Protocol Witness Matching Manifesto](https://github.com/apple/swift/blob/5413441cd448cfab1b77cc7af77b17eafa15eee6/docs/WitnessMatchingManifesto.md) > * 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](https://share.unison-lang.org/@unison/p/code/latest/namespaces/public/cloud/main/;/terms/betaProgram?viewMode=presentation) > We are looking for people to help us try out [unison.cloud](https://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](https://unison-lang.org/at-work) 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](https://share.unison-lang.org/@stew/p/code/latest/namespaces/public/projects/httpserver/main) > A Http server for the Unison Programming Language. * [Unison HTTP Client](https://share.unison-lang.org/@stew/p/code/latest/namespaces/public/projects/httpclient/main) > This is an HTTP client library. It can be used to make HTTP requests and inspect their responses. * [Unison Optics](https://share.unison-lang.org/@staccatosemibreve/p/code/latest/namespaces/public/optics/latest) > An attempt at an optics library for Unison — now with support for indexed and coindexed(!) optics! * [Unison Codec](https://share.unison-lang.org/@runarorama/p/code/latest/namespaces/public/codec/latest) > 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](https://github.com/unisonweb/unison/blob/trunk/docs/language-server.markdown) > **Supported features:** > * Autocompletion > * Inline type and parser error messages > * Show type on hover * [Memory Safe Languages in Android 13](https://security.googleblog.com/2022/12/memory-safe-languages-in-android-13.html) > To date, there have been zero memory safety vulnerabilities discovered in Android’s Rust code. * [allowsHitTesting(\_:)](https://developer.apple.com/documentation/swiftui/form/allowshittesting(_:)) > Configures whether this view participates in hit test operations. * [UIApplicationDelegateAdaptor](https://developer.apple.com/documentation/swiftui/uiapplicationdelegateadaptor) > A property wrapper type that you use to create a UIKit app delegate. * [PreviewProvider](https://developer.apple.com/documentation/swiftui/previewprovider) > A type that produces view previews in Xcode. * [Previews in Xcode](https://developer.apple.com/documentation/swiftui/previews-in-xcode) > Generate dynamic, interactive previews of your custom views. * [Improving the speed of incremental builds](https://developer.apple.com/documentation/xcode/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*](https://dev.to/ashgkwd/swift-ui-camera-app-without-using-uiview-or-ui-41o1) > 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](https://developer.android.com/courses/android-basics-compose/course) > 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](https://www.hackingwithswift.com/quick-start/swiftui/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](https://peterfriese.dev/posts/swiftui-previews-interactive) > 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](https://www.netguru.com/blog/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)](https://github.com/pointfreeco/xctest-dynamic-overlay/blob/a9daebf0bf65981fd159c885d504481a65a75f02/Sources/XCTestDynamicOverlay/Internal/RuntimeWarnings.swift#L4) > 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?](https://forums.swift.org/t/reliably-testing-code-that-adopts-swift-concurrency/57304) > 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](https://developer.apple.com/documentation/cloudkitjs/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 the `saveSubscription` method in [`CloudKit.Database`](https://developer.apple.com/documentation/cloudkitjs/cloudkit/database). * [CloudKit Remote Records](https://developer.apple.com/documentation/cloudkit/remote_records) > Use subscriptions and change tokens to efficiently manage modifications to remote records. > # 2022 ## December * [CRAttributes](https://github.com/munhitsu/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](https://developer.apple.com/library/archive/documentation/General/Conceptual/iCloudDesignGuide/Chapters/DesigningForKey-ValueDataIniCloud.html#//apple_ref/doc/uid/TP40012094-CH7) > 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](https://developer.apple.com/documentation/foundation/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`, and `NSDictionary`. * [All you need to know about CloudKit Art](https://iteo.com/blog/post/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 using `NSUbiquitousKeyValueStore` which also employs iCloud and doesn’t require configuring the CloudKit container. * [Good Spirits: Syncing Data Statelessly](http://archagon.net/blog/2018/09/03/good-spirits-persisting-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](https://appdecentral.com/2020/11/03/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](https://developer.apple.com/documentation/cloudkit/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](https://developer.apple.com/documentation/app_clips/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](https://developer.apple.com/documentation/cloudkitjs) > Provide access from your web app to your CloudKit app’s containers and databases. * [Module vs Product vs Target](https://forums.swift.org/t/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` vs `Foundation.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(...)` and `testTarget(...)`, 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” * [String to UInt32](https://gist.github.com/tkersey/d96f91a3f0dc86a052030f8bad3e1230) > ```"ptru”.utf8.reduce(0) { $0 << 8 | $1 }``` * [Faster Builds with Code Signing Hacks](https://eisel.me/signing) > 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](https://anvaka.github.io/vs) > 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](https://eisel.me/lld) > **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](https://eisel.me/lld#integrating-lld) 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](https://eisel.me/lld#integrating-lld) on how to integrate lld at present. If you aren’t familiar with linking, read about it [here](https://stackoverflow.com/questions/3322911/what-do-linkers-do) and look for the linking step at the end of your build logs. * [Measuring your iOS app’s true startup time in production (2018)](https://eisel.me/startup) > 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](https://techblog.izotope.com/2018/03/08/improving-your-ios-apps-launch-time) show you how to measure it with the debugger, using `DYLD_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](https://swiftwithmajid.com/2022/03/22/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](https://swiftwithmajid.com/2022/03/29/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](https://www.youtube.com/watch?app=desktop&v=IEEarQdiFxY) > 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](https://xcode.tips/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](https://holyswift.app/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](https://matteomanferdini.com/swift-url-components) > 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](https://developer.apple.com/tutorials/swiftui/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](https://swiftwithmajid.com/2021/03/24/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)](https://www.wwdcnotes.com/notes/wwdc22/110362) > **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](https://github.com/apple-oss-distributions/dyld/blob/main/doc/dyld4.md) > 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](https://swiftpackageindex.com/omaralbeik/Stores/main/documentation/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](https://holyswift.app/trie-in-swift-autocorrect-data-structure-now-you-know-what-to-blame) > 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](https://support.apple.com/en-in/guide/deployment/depba790e53/web) > 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](https://swiftwithmajid.com/2019/05/22/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](https://nyswifty.com) > **New York, 04/18 & 04/19, 2023** * [Toggle Changes/Repos](https://xcode.tips/toggle-changes-repos) >  > Toggle between changes and repositories in the Source Control navigator with the shortcut Command 2. * [Reveal In Changes Navigator](https://xcode.tips/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](https://github.com/apple/swift-evolution/tree/main/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?](https://forums.swift.org/t/why-does-apple-recommend-to-use-structs-by-default/62066) > 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.](https://swiftwithmajid.com/2022/12/14/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](https://developer.apple.com/documentation/packagedescription/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](https://cats.for.ai/program) > 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](https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/testing_with_xcode/chapters/A1-guidelines_writing_testable_code.html#//apple_ref/doc/uid/TP40014132-CH8-SW1) > 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](https://developer.apple.com/library/archive/samplecode/UnitTests/Introduction/Intro.html#//apple_ref/doc/uid/DTS40011742-Intro) 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` and `100`, inclusive, the test code for that method should pass the values `0`, `50`, and `100` 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` to `100`, inclusive, create test cases that pass the values `-1` and `101` 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](https://developer.apple.com/documentation/xctest/xctissue) > An object that represents a test failure, and includes source code call stacks for test reporting and investigation. * [Adding SQLCipher to Xcode Projects](https://www.zetetic.net/sqlcipher/ios-tutorial) > 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](https://scholar.archive.org) > **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](https://www.swift.org/blog/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](https://coduo.app) > Pair program and Chat in real-time. > Simple, fast and effective. * [Advanced Data Protection for iCloud](https://support.apple.com/guide/security/advanced-data-protection-for-icloud-sec973254c5f) > 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](https://www.matthiaspreu.com/posts/lambda-calculus-fundamentals) > * [Functions](https://www.matthiaspreu.com/posts/lambda-calculus-fundamentals/#functions) > * [Notation](https://www.matthiaspreu.com/posts/lambda-calculus-fundamentals/#notation) > * [Further notation details](https://www.matthiaspreu.com/posts/lambda-calculus-fundamentals/#further-notation-details) > * [α-Conversion](https://www.matthiaspreu.com/posts/lambda-calculus-fundamentals/#alpha-conversion) > * [β-Reduction](https://www.matthiaspreu.com/posts/lambda-calculus-fundamentals/#beta-reduction) > * [β normal form](https://www.matthiaspreu.com/posts/lambda-calculus-fundamentals/#the-beta-normal-form) > * [The identity function](https://www.matthiaspreu.com/posts/lambda-calculus-fundamentals/#the-identity-function) > * [Currying — Application of multiple arguments](https://www.matthiaspreu.com/posts/lambda-calculus-fundamentals/#currying---application-of-multiple-arguments) > * [Combinators](https://www.matthiaspreu.com/posts/lambda-calculus-fundamentals/#combinators) > * [Divergence — Never ending reduction](https://www.matthiaspreu.com/posts/lambda-calculus-fundamentals/#divergence---never-ending-reduction) > * [Basic arithmetic in lambda calculus](https://www.matthiaspreu.com/posts/lambda-calculus-fundamentals/#basic-arithmetic-in-lambda-calculus) > * [Church encoding](https://www.matthiaspreu.com/posts/lambda-calculus-fundamentals/#church-encoding) > * [The successor function](https://www.matthiaspreu.com/posts/lambda-calculus-fundamentals/#the-successor-function) > * [Addition](https://www.matthiaspreu.com/posts/lambda-calculus-fundamentals/#addition) > * [Multiplication](https://www.matthiaspreu.com/posts/lambda-calculus-fundamentals/#multiplication) > * [Typed lambda calculus](https://www.matthiaspreu.com/posts/lambda-calculus-fundamentals/#typed-lambda-calculus) > * [References](https://www.matthiaspreu.com/posts/lambda-calculus-fundamentals/#references) > > Lambda calculus is a formal system to study computable functions based on variable binding and substitution. Introduced in the [1930s by Alonzo Church](https://pdfs.semanticscholar.org/ee95/8b752cdfc62c16289cd8d3b7274a2e09b14e.pdf), it is (in its typed form) the fundamental concept of functional programming languages like [Haskell](https://www.haskell.org) and [Scala](https://www.scala-lang.org). 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](https://developer.apple.com/support/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](https://driftingin.space/posts/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](https://browsertech.com/bt-index), we found it rare for apps to use true CRDTs to power multiplayer collaboration. * [Prototyping SwiftUI interfaces with OpenAI's ChatGPT](https://www.createwithswift.com/prototyping-swiftui-interfaces-with-openais-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](https://nilcoalescing.com/blog/BringingPolymorphismToCodable) > Swift’s [protocol oriented programming](https://www.raywenderlich.com/6742901-protocol-oriented-programming-tutorial-in-swift-5-1-getting-started) 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](https://nilcoalescing.com/blog/ReducingTheCodableBoilerplate) in complex `Codable` situations. * [Native Network Monitoring In Swift](https://digitalbunker.dev/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](https://developer.apple.com/documentation/network/nwpathmonitor) > An observer that you use to monitor and react to network changes. * [dataTile for Simulator](https://underplot.com/dataTile) > `Forget debugging in console` > > Automatically replace messy logs with beautiful visual data. * [How to manage build settings using Xcode configuration files](https://www.danijelavrzan.com/posts/2022/11/xcode-configuration) > 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](https://www.pathsensitive.com/2019/07/the-best-refactoring-youve-never-heard.html) > 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](https://developer.apple.com/documentation/foundation/archives_and_serialization/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](https://developer.apple.com/documentation/swift/encodable) and [Decodable](https://developer.apple.com/documentation/swift/decodable) protocols on your custom types. Adopting these protocols lets implementations of the [Encoder](https://developer.apple.com/documentation/swift/encoder) and [Decoder](https://developer.apple.com/documentation/swift/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](https://developer.apple.com/documentation/swift/codable), which combines the `Encodable` and `Decodable` protocols. This process is known as making your types _codable_. * [We Fast-Tracked Our App Development With Kotlin Multiplatform Mobile](https://medium.com/motive-eng/we-fast-tracked-our-app-development-with-kotlin-multiplatform-mobile-952f2f4afd1) > 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 > ## November * [First Introduction to Cubical Type Theory](https://1lab.dev/1Lab.intro.html) > 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](https://gist.github.com/4np/f0e811bc0fdeb17186088c47d5bead5a) > How to use a `.xcconfig` file and a `.plist` with a Swift Package Manager based project. * [Exploring the iOS Live Activities API](https://blog.logrocket.com/exploring-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](https://blog.saeloun.com/2022/11/22/data-immutable-object.html) > 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](https://sourcediving.com/clean-waiting-in-xcuitest-43bab495230f) > At Cookpad, we wanted an extension method on `XCUIElement` similar to `XCTestCase.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](https://developer.apple.com/tutorials/app-dev-training/getting-started-with-scrumdinger) > Learn the essentials of iOS app development by building a fully functional app using SwiftUI. * [SwiftUI is convenient, but slow](https://notes.alinpanaitiu.com/SwiftUI%20is%20convenient,%20but%20slow) > 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)](https://github.com/apple/swift/blob/1f3e159cfe518fbb723230a4e8f562248d34d863/lib/Sema/DerivedConformanceCodable.cpp#L2033-L2043) > `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.](https://swiftwithmajid.com/2022/11/16/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](https://www.steveonstuff.com/2022/01/13/migrating-from-objc-to-swift.html) > * 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. * [What is the @objcMembers attribute? (2019)](https://www.hackingwithswift.com/example-code/language/what-is-the-objcmembers-attribute) > 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](https://tanaschita.com/20221031-managing-cache-when-working-with-urlsession-in-ios) > 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)](https://useyourloaf.com/blog/slow-app-startup-times) > 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 enabling `DYLD_PRINT_STATISTICS` much easier to understand. * [Diagnostic flags in Clang](https://clang.llvm.org/docs/DiagnosticsReference.html) > `This page lists the diagnostic flags currently supported by Clang.` * [ObjectIdentifier](https://developer.apple.com/documentation/swift/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](https://gist.github.com/gdavis/218a37c623f650127a2ea1bc2f610151) > 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](https://kotlinlang.org/docs/apple-framework.html) > 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](https://frontendmastery.com/posts/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](https://holyswift.app/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?](https://dougallj.wordpress.com/2022/11/09/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](https://kean.blog/post/xcframeworks-caveats) > 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?](https://tiagolopes.blog/2022/11/01/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? > > 1. Dispose of any SwiftUI View values not used anymore > 1. Dispose of any UIHostingController references not used anymore > 1. 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 > ## October * [ComposableArchitecture Documentation](https://pointfreeco.github.io/swift-composable-architecture/main/documentation/composablearchitecture) > 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](https://www.pointfree.co/blog/posts/83-non-exhaustive-testing-in-the-composable-architecture) > Testing is by far the #1 priority of the [Composable Architecture](http://github.com/pointfreeco/swift-composable-architecture). The library provides a tool, the [TestStore](https://pointfreeco.github.io/swift-composable-architecture/main/documentation/composablearchitecture/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](http://merowing.info) and support from his employer, [The Browser Company](https://thebrowser.company), the [0.45.0](https://github.com/pointfreeco/swift-composable-architecture/releases/tag/0.45.0) release of the library brings first class support for “non-exhaustive” test stores. * [Create a bootable Ventura USB drive using Terminal](https://setapp.com/how-to/create-bootable-ventura-installer) > Another method to make a bootable USB drive is createinstallmedia command in Terminal. > 1. Rename USB Volume to MyVolume > 1. 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](https://mrmacintosh.com/macos-ventura-13-full-installer-database-download-directly-from-apple) > 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](https://wojciechkulik.pl/ios/swift-concurrency-things-they-dont-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 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. * [Decentralized Social Networking Protocol (DSNP) specification](https://spec.dsnp.org) > 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. * [YOU MIGHT NOT NEED JAVASCRIPT](http://youmightnotneedjs.com) > 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. * [Apple Security Research](https://security.apple.com) > 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. * [Xcode 14 Single Size App Icon](https://useyourloaf.com/blog/xcode-14-single-size-app-icon) > 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](https://wojciechkulik.pl/ios/swift-concurrency-things-they-dont-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. * [Swift Compiler Driver](https://github.com/apple/swift-driver) > 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](https://github.com/apple/swift/blob/main/docs/Driver.md) > 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](https://github.com/apple/swift/blob/main/docs/DriverInternals.md) > 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](https://github.com/apple/swift/blob/main/docs/DriverParseableOutput.md) > 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](https://iosref.com) > iOS Ref was created in January 2018 by [me](https://ebelinski.com) to serve as a one-stop quick reference spot for iOS developers. * [Where View.task gets its main-actor isolation from](https://oleb.net/2022/swiftui-task-mainactor) > SwiftUI’s [`.task` modifier](https://developer.apple.com/documentation/swiftui/view/task(priority:_:)) inherits its actor context from the surrounding function. If you call `.task` inside a view’s `body` property, the async operation will run on [the main actor](https://developer.apple.com/documentation/swift/mainactor) because `View.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](https://tanaschita.com/20221010-quick-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. * [Codeface](https://apps.apple.com/app/id1578175415) > 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](https://nilcoalescing.com/blog/CheckIfTwoValuesOfTypeAnyAreEqual) > 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 to `any Equatable` and also use `any Equatable` as a parameter type thanks to [Unlock existentials for all protocols](https://github.com/apple/swift-evolution/blob/main/proposals/0309-unlock-existential-types-for-all-protocols.md) change. * [`@StateObject` vs. `@ObservedObject`: The differences explained](https://www.avanderlee.com/swiftui/stateobject-observedobject-differences) > `@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](https://belkadan.com/blog/2022/10/Swift-in-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](https://belkadan.com/blog/2022/02/Dynamic-Linking-and-Static-Linking) > 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.](https://swiftwithmajid.com/2022/10/05/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:)`](https://developer.apple.com/documentation/swift/withthrowingtaskgroup(of:returning:body:)) > Starts a new scope that can contain a dynamic number of throwing child tasks. * [Rive](https://rive.app) > The new standard for interactive graphics > > Blazing fast. Tiny size. Runs everywhere. > ## September * [Universals to the right, Existentials to the left: the adjoint triple "Exists ⊣ Const ⊣ Forall"](https://www.reddit.com/r/haskell/comments/jdjdnl/universals_to_the_right_existentials_to_the_left) > `Exists @k ⊣ Const @k ⊣ Forall @k` * [How To Deploy a Kotlin API With http4k and Heroku](https://8thlight.com/blog/selina-chang-yi-zawacki/2022/01/25/deploy-a-kotlin-api-with-http4k-and-heroku.html) > 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](https://www.merowing.info/boundries-in-tca) > 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](https://developer.apple.com/documentation/widgetkit/dynamicisland) > The layout and configuration for a Live Activity that appears in the Dynamic Island. * [SwiftUI Navigation & URL Routing — Brandon Williams](https://vimeo.com/751580644) > 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](https://www.youngwonks.com/blog/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](https://topos.site/blog/2022/09/nates-adjoint-5-tuple) > In August, Nate Soares visited Topos Institute. We told him a little about `Poly` and `Proly` Proly and he told us about what he wanted from a type theory. * [Mastering Dynamic Island in SwiftUI](https://swiftwithmajid.com/2022/09/28/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)](https://developer.apple.com/design/human-interface-guidelines/components/system-experiences/live-activities) > 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](https://1lab.dev/Cat.Instances.Poly.html) > 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](https://artandscienceofcoding.com/science/kmm-for-ios-engineers) > * 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](https://swiftwithmajid.com/2022/09/21/displaying-live-activities-in-ios16) > 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](https://betterprogramming.pub/simplify-your-react-components-state-with-a-state-machine-8e9c9a4ee1f6) > Use a reducer to implement a fully-typed state machine without breaking a sweat. * [Composable Architecture @ Scale](https://www.merowing.info/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.`](https://twitter.com/__steele/status/1570208081296134145) > 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](https://rensbr.eu/blog/swiftui-diffing) > * **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 by `ViewBuilder`, such as `TupleView` 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 type `ModifiedContent`. * [What's the "any" keyword? Understanding Type Erasure in Swift](https://swiftrocks.com/whats-any-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](https://medium.com/fashioncloud/a-functional-programming-approach-to-error-handling-in-typescript-d9e8c58ab7f) > 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](https://bobbyhadz.com/blog/typescript-arrow-function-generic) > > ```typescript > const returnInArray = <T>(value: T): T[] => [value]; > ``` > * [Domain Driven Design using GADTs](https://dnikolovv.github.io/practical-haskell-ddd-gadt) > 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%](https://www.emergetools.com/blog/posts/improve-popular-iOS-app-startup-times) > **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](https://support.apple.com/en-us/HT202704) > **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](http://mysupport.apple.com/). > * The serial number of the device that the plan covers. [Learn how to find the serial number](https://support.apple.com/kb/HT204308). > * Your original sales receipt. * [The SwiftUI Layout Protocol – Part 1](https://swiftui-lab.com/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](https://swiftui-lab.com/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](https://support.apple.com/en-us/HT213317) > Learn about changes and features included in the firmware updates for your AirPods. * [TIL: You Can Access A User’s Camera with Just HTML](https://austingil.com/html-capture-attribute) > 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](https://holyswift.app/exploring-swiftui-redraw-behavior-with-instruments) > 1. Be careful using the `@ObservedObject` in all your views, use it only when it is needed. > 2. It is not because is working that your code is **optimal**. > 3. While working with SwiftUI check what views are redrawing with **Instruments** and if all your redraws are intended. * [Improving Composable Architecture performance](https://www.pointfree.co/blog/posts/80-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?](https://www.clariontech.com/blog/app-development-cost) > 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](https://stevejobsarchive.com) > 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](https://developer.apple.com/documentation/uikit/uiwindow/3987976-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](https://jsoncrack.com) > Seamlessly visualize your JSON data instantly into graphs. * [Three UIKit Protips](https://blog.steveasleep.com/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: > > 1. An `addSubviews` method to define your view hierarchy all at once > 2. An `@AssignedOnce` property wrapper > 3. A pattern for keeping view creation at the bottom of a file to keep the top clean * [Using CoordinateSpace to draw over a SwiftUI List](https://daringsnowball.net/articles/swiftui-coordinatespace) > In `UIKit`, we would use `UICoordinateSpace.convert(_,to:)` or the older `UIView.convert(_,to:)` functions, and happily there's a SwiftUI equivalent in `CoordinateSpace`. * [Create Live Activities With ActivityKit on iOS 16](https://betterprogramming.pub/create-live-activities-with-activitykit-on-ios-16-beta-4766a347035b) > 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](https://www.jessesquires.com/blog/2022/08/19/sharing-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 and `NSPasteboard` on macOS. * [Xcode's refactoring options for async/await](https://blog.eidinger.info/xcodes-refactoring-options-for-asyncawait) > Automatically adopt async functions in your codebase with ease * [Sourcery Swift Package command plugin](https://www.polpiella.dev/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. > ## August * [GHCi List of commands](https://typeclasses.com/ghci/commands) > 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](https://www.avanderlee.com/swiftui/viewbuilder) > 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](https://nilcoalescing.com/blog/AdjustTheDirectionOfFocusBasedNavigation) > 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](https://sarunw.com/posts/swiftui-viewthatfits) > Making SwiftUI views responsive usually involves a lot of `GeometryReaders` and `if-else`. > > In iOS 16, SwiftUI got a new view that makes it easier to create a responsive layout, `ViewThatFits`. > 1. `ViewThatFits` apply `fixedSize()` on each child view, starting from the top. > 2. If the child view ideal size is **larger than the parent's proposed size**, `ViewThatFits` evaluate the **next child**. > 3. Then it **returns the first child that fits within the proposed size**. * [AppKit is Done](https://kean.blog/post/appkit-is-done) > 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)](https://github.com/pointfreeco/swift-composable-architecture/blob/protocol-beta/Sources/ComposableArchitecture/Documentation.docc/Articles/MigratingToReducerProtocols.md) > 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](https://github.com/pointfreeco/swift-composable-architecture/blob/108e3a536fcebb16c4f247ef92c2d7326baf9fe3/Sources/ComposableArchitecture/Documentation.docc/Articles/Performance.md) > 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](https://blog.nihongo-app.com/stop-xcode-14-beta-from-pegging-cpu) > 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)](https://qualitycoding.org/swift-test-assertions) > 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](https://tanaschita.com/20220822-bridge-async-await-to-combine-future) > Learn how to call async/await code within Combine based APIs. * [withLock(_:)](https://developer.apple.com/documentation/foundation/nslocking/4059821-withlock) > `func withLock<R>(_ body: () throws -> R) rethrows -> R` * [Keeping a widget up to date efficiently on iOS](https://codakuma.com/widgetkit-improvements) > * **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](https://matteomanferdini.com/install-xcode) > 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)](https://swiftwithmajid.com/2021/12/09/structural-identity-in-swiftui) > 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)](https://swiftwithmajid.com/2019/11/19/you-have-to-change-mindset-to-use-swiftui) > 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. * [Installing Swift](https://www.swift.org/server/guides/setup-and-ide-alternatives.html) > 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. * [Build System](https://www.swift.org/server/guides/building.html) > 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. * [Testing](https://www.swift.org/server/guides/testing.html) > 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. * [Debugging Performance Issues](https://www.swift.org/server/guides/performance.html) > 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](https://www.swift.org/server/guides/deployment.html) > 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](https://www.swift.org/server/guides/packaging.html) > 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. * [LLVM TSAN / ASAN](https://www.swift.org/server/guides/llvm-sanitizers.html) > 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](https://holyswift.app/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](https://swiftwithmajid.com/2022/08/16/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](https://blog.ret2.io/2022/08/17/macos-dblmap-kernel-exploitation) > 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. * [Suspicious Package](https://www.mothersruin.com/software/SuspiciousPackage) > An Application for Inspecting macOS Installer Packages * [`withUnsafeTemporaryAllocation(of:capacity:_:)`](https://developer.apple.com/documentation/swift/withunsafetemporaryallocation(of:capacity:_:)) > Provides scoped access to a buffer pointer to memory of the specified type and with the specified capacity. * [swiftinit](https://swiftinit.org) > 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](https://hacknicity.medium.com/view-controller-presentation-changes-in-ios-and-ipados-16-474c82c9ed2e) > 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](https://gregoryszorc.com/blog/2022/08/08/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](https://blog.hachi.one/post/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](https://slack.engineering/stabilize-modularize-modernize-scaling-slacks-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](https://slack.engineering/stabilize-modularize-modernize-scaling-slacks-mobile-codebases-2) > 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](https://slack.engineering/scaling-slacks-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](https://oleb.net/2022/live-activity) > "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?](https://www.thealexanderlee.com/blog/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](https://diggingdeveloper.blog/2022/08/03/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` or `expression`. * [KeyPathComparator](https://developer.apple.com/documentation/foundation/keypathcomparator) > 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](https://nilcoalescing.com/blog/SortElementsBasedOnAPropertyValueUsingKeyPathComparator) > 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](https://www.avanderlee.com/swift/sendable-protocol-closures) > 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. > ## July * [Monad Confusion and the Blurry Line Between Data and Computation](https://www.micahcantor.com/blog/monad-confusion) > 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](https://holyswift.app/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](https://quokkalabs.com/blog/ios-vs-android-apps-ui-difference) > 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](https://developer.apple.com/documentation/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](https://developer.apple.com/documentation/activitykit/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](https://developer.apple.com/documentation/activitykit/activity) > The object you use to start, update, and end a Live Activity. * [TYPE-SIGNATURE](https://type-signature.com) > It's basically `"Who Wants to Be a Millionaire?"` — but with types. * [NavigationSplitView](https://developer.apple.com/documentation/swiftui/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](https://fuckingformatstyle.com) > 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](https://developer.apple.com/documentation/swiftui/labeledcontent) > A container for attaching a label to a value-bearing view. * [Mastering LabeledContent in SwiftUI](https://swiftwithmajid.com/2022/07/13/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](https://ampersandsoftworks.com/posts/from-strings-to-data-using-parseableformatstyle) > 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](https://gist.github.com/brettohland/744fcbd2a8aa77907ec84a286e8da3b0) > 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](https://ampersandsoftworks.com/posts/formatstyle-parseableformatstyle-and-your-custom-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](https://www.swiftbysundell.com/articles/switching-between-swiftui-hstack-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. > ```swift 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 )) } } ``` * [InspectableNavigationPath.swift](https://gist.github.com/tgrapperon/1fd9ee1addd598ec24ddb382ad685f5a) ```swift 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**](https://gist.github.com/tkersey/b145e8fd242ff4991acd596c54d10f5d) > Variously useful CLI commands such as downloading and creating USB installers * [GenerateFake.sourcerytemplate](https://gist.github.com/tkersey/d1ad239daec1ab4c9f88f5ecc4e621ec) > Sourcery Template for Generating fakes * [What's New in Xcode 14 Previews](https://useyourloaf.com/blog/whats-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](https://swiftui-lab.com/swiftui-renders) > 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](https://developer.apple.com/documentation/swiftui/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](https://www.swift.org/blog/swift-language-updates-from-wwdc22)** >  * [Getting UIKit's UICalendarView from iOS 16 fully functioning in a SwiftUI app](http://chriswu.com/posts/swiftui/uicalendarview) > 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](https://swiftly.dev) > Swift references for busy coders * [SwiftUI Renderers and Their Tricks](https://swiftui-lab.com/swiftui-renders) > 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)](https://blog.metaobject.com/2018/12/uis-are-not-pure-functions-of-model.html) > 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](https://take.surf/2022/07/04/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](https://developer.apple.com/documentation/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](https://twitter.com/jckarter/status/1355916944403095554) * [Large structs and stack overflow (code)](https://gist.github.com/tkersey/46489cef0b91522ee6658b03d91684c8) > Reducing stack costs of structs by using Copy on Write (CoW) * [Large structs and stack overflow (forum)](https://forums.swift.org/t/large-structs-and-stack-overflow/44820) > 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](https://www.youtube.com/watch?v=iLDldae64xE) > 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](https://hyperdbg.github.io/commands-map) > Below is a table of equivalent debugger commands for the GDB, LLDB, WinDbg (CDB), and HyperDbg debuggers. > ## June * [My first contribution to Homebrew](https://github.com/Homebrew/homebrew-core/commit/9d732bf701690b52a0cdfe5bafa5cf8cc81164a9) * New Formula: GOCR * [Model View Controller Store: Reinventing MVC for SwiftUI with Boutique](https://build.ms/2022/06/22/model-view-controller-store) > 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 Index](https://mackuba.eu/swiftui/changelog) > SwiftUI Changelog * [SiriTipView](https://developer.apple.com/documentation/appintents/siritipview) > 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](https://webauthn.guide) > 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.](https://swiftwithmajid.com/2022/06/15/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)](https://blog.timing.is/wwdc-22-digital-design-lounge-archive) > 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! * [#HEXWORDS](https://hexwords.netlify.app) > Why bother with a random green when you can choose to be a #BADA55! * [App Clips Diagnostic Tool](https://developer.apple.com/videos/play/wwdc2022-10097/?time=144) > 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](https://developer.apple.com/videos/play/wwdc2022/10077) > 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](https://developer.apple.com/videos/play/wwdc2022/110351) > 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](https://developer.apple.com/videos/play/wwdc2022/10142) > 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](https://developer.apple.com/videos/play/wwdc2022/110364) > 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](https://developer.apple.com/videos/play/wwdc2022/110370) > 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. * [Resizable Sheet in SwiftUI](https://nilcoalescing.com/blog/ResizableSheetInSwiftUI) > 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](https://developer.apple.com/videos/play/wwdc2022/110353) > 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:)](https://developer.apple.com/documentation/swiftui/presentedwindowcontent/navigationdestination(for:destination:)) > Associates a destination view with a presented data type for use within a navigation stack. * [About the security of passkeys](https://support.apple.com/en-us/HT213305) > 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](https://developer.apple.com/videos/play/wwdc2022/10056) > 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](https://developer.apple.com/documentation/swiftui/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. * [NavigationStack](https://developer.apple.com/documentation/swiftui/navigationstack) > 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](https://developer.apple.com/documentation/widgetkit/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. * [Embrace Swift generics](https://developer.apple.com/videos/play/wwdc2022/110352) > 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](https://developer.apple.com/videos/play/wwdc2022/10054) > 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. * [Supporting Passkeys](https://developer.apple.com/documentation/authenticationservices/public-private_key_authentication/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. * [Link fast: Improve build and launch times](https://developer.apple.com/videos/play/wwdc2022/110362) > 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](https://developer.apple.com/videos/play/wwdc2022/110363) > 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](https://developer.apple.com/videos/play/wwdc2022/110356) > 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](https://developer.apple.com/videos/play/wwdc2022/110364) > 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](https://developer.apple.com/videos/play/wwdc2022/110339) > 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. * [Use SwiftUI with UIKit](https://developer.apple.com/videos/play/wwdc2022/10072) > 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)](https://developer.apple.com/documentation/uikit/views_and_controls/using_swiftui_with_uikit) > Learn how to incorporate SwiftUI views into a UIKit app. * [Enabling Developer Mode on a device](https://developer.apple.com/documentation/xcode/enabling-developer-mode-on-a-device) > Grant or deny permission for locally installed apps to run on iOS, iPadOS, and watchOS devices. * [HTTP Live Streaming](https://developer.apple.com/streaming) > 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](https://developer.apple.com/documentation/http_live_streaming/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)](https://developer.apple.com/videos/play/wwdc2019/502) > 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. * [AttributedString.swift](https://gist.github.com/chockenberry/ad744bacdc14a750e02e93063d0dc20a) > A playground that shows how to use Swift's AttributedString with Markdown > ## May * [SwiftUI Property Wrappers](https://swiftuipropertywrappers.com) > Deciding when to use each of SwiftUI's key property wrappers > <img width="1788" alt="decision_draft" src="https://user-images.githubusercontent.com/217/171195963-305c2486-96e9-4a73-b461-2f85c418c23d.png"> * [Identity Pinning: How to configure server certificates for your app](https://developer.apple.com/news/?id=g9ejcf8y) > 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)](https://nilcoalescing.com/tags/tips) > Swift/iOS tips and tricks * [Detecting SwiftUI preview mode](https://danielsaidi.com/blog/2022/05/27/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](https://sakunlabs.com/blog/swiftui-identity-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](https://engineering.empower.me/faster-xcode-builds-when-switching-branches-67133ccfdc33) > 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](https://saurabhs.org/macos-tips) > 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](https://github.com/chirag05k/Xcode-Shortcuts) > Visual Xcode shortcuts which will help to speed up your development 🚀. * [Copy Images from Storyboards and XIBs](https://twitter.com/pilky/status/1524684050652446720) > 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](https://rensbr.eu/blog/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](https://danielsaidi.com/blog/2022/05/06/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](https://oleb.net/2022/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](https://johnholdsworth.com/dyld_dynamic_interpose.html) > 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](https://jott.live/markdown/wasm_binary_size) > 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](https://christiantietze.de/posts/2022/05/weak-self-consistency) > 1. Only use a strong self for non-@escaping closures (ideally, omit it & trust the compiler) > 2. Use weak self if you’re not sure > 3. Upgrade self to a strongly-retained self at the top of your closure. > ## April * [How much does more memory benefit Xcode?](https://twitter.com/cocoawithlove/status/1517736163318009856) > 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](http://www.alwaysrightinstitute.com//viewcontroller) > 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](https://johnoreilly.dev/posts/swift-async-algorithms-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](https://twitter.com/Catfish_Man/status/1516909101149671424) > 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](http://defagos.github.io/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](https://useyourloaf.com/blog/dismissing-swiftui-views) > SwiftUI has a less clumsy mechanism for dismissing presented views in iOS 15. * [SwiftUI performance tips](https://martinmitrevski.com/2022/04/14/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. > ## March * [Replicating Types in Swift](https://appdecentral.com/posts-in-the-replicating-types-crdts-in-swift-series) > 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](https://github.com/apps/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](https://chris.eidhof.nl/post/swiftui-state-lifetime) > 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)](https://github.com/thebrowsercompany/swift-composable-architecture/blob/develop/Sources/ComposableArchitecture/TestSupport/TBCTestStore.swift) > 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`](https://developer.apple.com/documentation/xcode-release-notes/xcode-13_3-release-notes#Build-System) > 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`](https://developer.apple.com/documentation/xcode-release-notes/xcode-13_3-release-notes#Swift-Packages) > Making changes to one or more packages in a workspace and then starting a build may cause Xcode to crash. * **xcdebug** > <img width="1182" alt="Foo" src="https://user-images.githubusercontent.com/217/158909281-10986bcc-1dbb-409c-9144-0a6f58c2cc2b.png"> * [Development & design tools for iOS developers](https://twitter.com/onmyway133/status/1504487759649525767) > 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](https://www.wtfautolayout.com) > Demystify Auto Layout constraint error logs * [NSDateFormatter](https://nsdateformatter.com) > Easy Skeezy Date Formatting for Swift and Objective-C * [Quick Type](https://app.quicktype.io) > Convert JSON to Swift code * [Screen Sizes](https://www.screensizes.app) > A complete guide for Apple displays * [Cubic Bezier](https://cubic-bezier.com) > Play around with bezier path * [Regex101](https://regex101.com) > 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](https://www.happyhues.co) > 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](https://mobbin.design) > Design screenshots collection * [Paywall](https://www.paywallscreens.com) > Curation of paywall screens * [Checklist Design](https://www.checklist.design) > A collection of the best design practices. * [Give your iOS Simulator superpowers](https://sherlock.inspiredcode.io) > Give your iOS Simulator superpowers * [FengNiao](https://github.com/onevcat/FengNiao) > A command line tool for cleaning unused resources in Xcode. * [Build Time Analyzer for Xcode](https://github.com/RobertGummesson/BuildTimeAnalyzer-for-Xcode) > Build Time Analyzer for Swift * [DevCleaner](https://github.com/vashpan/xcode-dev-cleaner) > 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](https://twitter.com/twostraws/status/1501973333998555148) > `defaults write http://com.apple.dt.Xcode ShowBuildOperationDuration YES` * [How to debug allocation regressions](https://github.com/apple/swift-nio/blob/main/docs/debugging-allocations.md) > 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](https://github.com/Losiowaty/PlaygroundTester) > PlaygroundTester enables you to easily run tests for your iPad Playgrounds 4 project. * [Better performance with canvas in SwiftUI](https://swdevnotes.com/swift/2022/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](https://peterfriese.dev/posts/swiftui-combine-custom-operators) > 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. ## February * [Native Network Monitoring In Swift](https://digitalbunker.dev/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](https://redmonk.com/jgovernor/2022/02/21/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](https://www.polpiella.dev/embedding-a-dylib-in-a-swift-package) * [Xcode Tips](https://xcode.tips) > Collections of tips for Xcode. * [UIKit Catalog: Creating and Customizing Views and Controls](https://developer.apple.com/documentation/uikit/views_and_controls/uikit_catalog_creating_and_customizing_views_and_controls) > Customize your app’s user interface with views and controls. * [VirtualFileSystem.swift](https://github.com/apple/swift-package-manager/blob/main/Sources/Basics/VirtualFileSystem.swift) > allows to load a package from a serialized form * [customPackageContainerProvider](https://github.com/apple/swift-package-manager/blob/main/Sources/Workspace/Workspace.swift#L310) > a custom package container provider * [Debugging SwiftUI views: what caused that change?](https://www.avanderlee.com/swiftui/debugging-swiftui-views) > 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](https://hybridcattt.com/blog/fixing-swiftui-previews) > 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](https://asifmohd.github.io/ios/2022/02/03/bloaty-ios-introduction.html) > 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](https://github.com/apple/swift/blob/main/docs/Lexicon.md) > 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.](https://swiftwithmajid.com/2022/01/26/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. > ## January * [A type can be Sendable if _any_ of these three conditions is true](https://twitter.com/beccadax/status/1471713250282672131) 1. It has no mutable state 2. It has mutable state, but `=` creates a copy of that state that doesn't share anything with the original 3. 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](https://discussions.apple.com/docs/DOC-250003311) > 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](https://support.apple.com/en-us/HT201295) > 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](https://support.apple.com/en-us/HT204063) > 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](https://www.polpiella.dev/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](https://developer.apple.com/support/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](https://eternalstorms.at/backlog) > 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](https://tiagomaia.blog/2022/01/16/the-structure-of-a-swift-package) > Explore packages in more detail * [MacOS screenshotting tips](https://twitter.com/DLX/status/1483397595577950211) > `⇧⌘4, then space, then hold ⌘ to screenshot individual panels and floating windows.` * [Cascading Environment actions in SwiftUI](https://www.magnuskahr.dk/posts/2021/12/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](https://www.donnywals.com/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](https://bootstragram.com/blog/swift-precondition-that-throws) > Checks a necessary condition for making forward progress. * [Loading Media Data Asynchronously](https://developer.apple.com/documentation/avfoundation/media_assets_and_metadata/loading_media_data_asynchronously) > Simplify asynchronous property loading using language-level concurrency features. * [App Startup Time: Past, Present, and Future (2017)](https://developer.apple.com/videos/play/wwdc2017/413) > 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)](https://youtu.be/PxV34oZxGLM) > <img width="1193" alt="Screen Shot 2022-01-05 at 11 25 33 AM" src="https://user-images.githubusercontent.com/217/148276782-a8d0a0b5-5984-4ddd-8acd-f42c258731de.png"> > <img width="1528" alt="Screen Shot 2022-01-04 at 4 35 07 PM" src="https://user-images.githubusercontent.com/217/148142440-980966a9-6a76-4310-b297-9005d6e5dca5.png"> > <img width="1434" alt="Screen Shot 2022-01-04 at 4 49 39 PM" src="https://user-images.githubusercontent.com/217/148143426-ac1eb7a5-8523-4345-b591-00da6162f652.png"> > <img width="1193" alt="Screen Shot 2022-01-04 at 4 53 22 PM" src="https://user-images.githubusercontent.com/217/148143673-6f6983bc-632e-4193-9e83-6ec7884c21ae.png"> > <img width="1182" alt="Screen Shot 2022-01-04 at 4 57 07 PM" src="https://user-images.githubusercontent.com/217/148144018-f8a1cf17-0500-48e8-9257-7343176060fa.png"> > <img width="1535" alt="Screen Shot 2022-01-05 at 11 13 42 AM" src="https://user-images.githubusercontent.com/217/148275307-04939acd-9651-4ef1-8128-018bcb7522aa.png"> > <img width="1609" alt="Screen Shot 2022-01-05 at 11 20 04 AM" src="https://user-images.githubusercontent.com/217/148276129-e6dd6d1f-3038-430b-8e0e-095ed3453e34.png"> > <img width="1522" alt="Screen Shot 2022-01-05 at 11 23 53 AM" src="https://user-images.githubusercontent.com/217/148276614-b7a929b5-40b0-4ec9-9596-eec9f817dfc5.png"> * [Method dispatch in Swift (2017)](https://trinhngocthuyen.github.io/posts/tech/method-dispatch-in-swift) > 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. > <img width="739" alt="Screen Shot 2022-01-03 at 11 12 20 AM" src="https://user-images.githubusercontent.com/217/147970213-0ccd7304-59d1-4f2c-88d2-498eeeb3d760.png"> > # 2021 ## December * [Meet AsyncSequence (2021)](https://developer.apple.com/videos/play/wwdc2021/10058) > 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. > <img width="1904" alt="Screen Shot 2021-12-29 at 3 59 56 PM" src="https://user-images.githubusercontent.com/217/147711668-32b54d9b-5232-4b96-865c-18079ca1b3a0.png"> * [Understanding Swift Performance (2016)](https://developer.apple.com/videos/play/wwdc2016/416) > 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. > ## 2021 Previous organization #### API * [Web API Client in Swift](https://kean.blog/post/new-api-client) > 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. > #### Apps * [Pulse: Structured Logging System](https://github.com/kean/Pulse) > 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](https://merowing.info/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. > #### App Store * [AppStoreReviewGuidelinesHistory](http://www.appstorereviewguidelineshistory.com) #### Automation * [https://github.com/twostraws/Sitrep](https://github.com/twostraws/Sitrep) > a source code analyzer for Swift projects, giving you a high-level overview of your code > #### Code * [Debug Overrides](https://gist.github.com/zats/cb3d9f48cd97571c01958cf145766f94) > 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](https://developer.apple.com/documentation/vision/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](https://developer.apple.com/documentation/authenticationservices/connecting_to_a_service_with_passkeys) > Allow users to sign in to a service without typing a password. > #### Debugging * [How To Solve Any iOS Crash Ever](https://swiftrocks.com/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! > #### Documentation * [30 tips to make you a better iOS developer](https://www.fadel.io/blog/posts/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](https://developer.apple.com/documentation/xcode/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](https://developer.apple.com/documentation/xcode/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](https://developer.apple.com/documentation/swift/choosing_between_structures_and_classes) > Decide how to store data and model behavior. * [Reducing Your App’s Size](https://developer.apple.com/documentation/xcode/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](https://mcyoung.xyz/2021/06/01/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?](https://lwn.net/Articles/276782) > 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](https://developer.apple.com/documentation/uikit/app_and_environment/responding_to_the_launch_of_your_app/about_the_app_launch_sequence#3894431) > 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](https://developer.apple.com/documentation/xcode/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](https://developer.apple.com/documentation/bundleresources/information_property_list/itsappusesnonexemptencryption) > A Boolean value indicating whether the app uses encryption. * [Deal with nested SPM errors](https://gist.github.com/tkersey/dccf5064b29dbf661c5afb5d0036dc31) > <https://forums.swift.org/t/swift-packages-in-multiple-targets-results-in-this-will-result-in-duplication-of-library-code-errors/34892/67> * [Convert a Universal (FAT) Framework to an XCFramework](https://medium.com/strava-engineering/convert-a-universal-fat-framework-to-an-xcframework-39e33b7bd861) > 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](https://developer.apple.com/documentation/metrickit/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](https://gankra.github.io/blah/compact-unwinding/) > 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](https://developer.apple.com/documentation/uikit/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](https://machinelearning.apple.com) * [Underscored Attributes Reference](https://github.com/apple/swift/blob/main/docs/ReferenceGuides/UnderscoredAttributes.md) > 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. > #### Forums * [What is garbage collection? — Chris Lattner (2016)](https://forums.swift.org/t/what-about-garbage-collection/1360/6) > 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)](https://forums.swift.org/t/swift-performance/28776/100) > 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.) > #### Functional Programming * [Why Mondads? (2017)](https://broomburgo.github.io/fun-ios/post/why-monads) #### Foundation * [How Expensive is DateFormatter](https://sarunw.com/posts/how-expensive-is-dateformatter) #### iOS * [Optimizing ProMotion Refresh Rates for iPhone 13 Pro and iPad Pro](https://developer.apple.com/documentation/quartzcore/optimizing_promotion_refresh_rates_for_iphone_13_pro_and_ipad_pro) > Provide custom animated content for ProMotion displays. > #### LLVM * [LLVM Internals: the bitcode format](https://blog.yossarian.net/2021/07/19/LLVM-internals-part-1-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. > #### News * [5 iOS Frameworks: Experts Suggest Which Ones to Master](https://insights.dice.com/2021/03/29/5-ios-frameworks-experts-suggest-which-ones-to-master) #### Simulator * [Deleting your app from the iOS simulator during UI tests](https://www.jessesquires.com/blog/2021/10/25/delete-app-during-ui-tests) > resetting your app between UI tests by completely deleting it > #### Objective-C * [Bypassing objc_msgSend (2019)](https://saagarjha.com/blog/2019/12/15/bypassing-objc-msgsend) > 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 of `objc_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. > #### Swift * [What's .self, .Type and .Protocol? Understanding Swift Metatypes (2018)](https://swiftrocks.com/whats-type-and-self-swift-metatypes) > 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](https://knight.sc/reverse%20engineering/2019/07/17/swift-metadata.html) > 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](https://kastiglione.github.io/builds/2021/11/12/faster-swift-and-clang-builds.html) > This is a collection of suggestions that reduce the time it takes to build the Swift and Clang compilers. * [SwiftCodeSan](https://github.com/uber/SwiftCodeSan) > SwiftCodeSan is a tool that "sanitizes" code written in Swift. > #### SwiftUI * [Understanding how and when SwiftUI decides to redraw views](https://www.donnywals.com/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](https://www.fivestars.blog/articles/swiftui-environment-values) > 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](https://apurin.me/articles/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 the `body` function of your view. * [Abstracting Navigation in SwiftUI](https://obscuredpixels.com/abstracting-navigation-in-swiftui) * [A sneak peek into SwiftUI's graph](https://fivestars.blog/swiftui/swiftui-graph.html) * [AppKit is Done](https://kean.blog/post/appkit-is-done) * [The Strategic SwiftUI Data Flow Guide (+ Infographic)](https://matteomanferdini.com/swiftui-data-flow) * [Call `Self._printChanges()` inside the body of a view to print out the changes that have triggered the view update.](https://twitter.com/luka_bernardi/status/1402045202714435585) #### SPM * [SwiftLint for Swift Packages](https://blog.timac.org/2021/1003-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](https://danielsaidi.com/blog/2021/02/15/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](https://developer.apple.com/documentation/swift_packages/bundling_resources_with_a_swift_package) > Add resource files to your Swift package and access them in your code. > #### The Composable Architecture * [fireAndCatch - For ignoring Output, while catching Failures](https://github.com/pointfreeco/swift-composable-architecture/pull/436/files) > Turns any publisher into an `Effect` for any output and failure type by ignoring all output, but retaining any failure. > #### Tools * [IPATool](https://github.com/majd/ipatool) > Command-line tool that allows searching and downloading app packages (known as ipa files) from the iOS App Store > #### WWDC * [ARC in Swift: Basics and beyond](https://developer.apple.com/videos/play/wwdc2021/10216) > 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](https://developer.apple.com/videos/play/wwdc2021/10212/) > 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](https://developer.apple.com/videos/play/wwdc2021/10022/) > 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](https://developer.apple.com/videos/play/wwdc2021/10180/) > 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](https://developer.apple.com/videos/play/wwdc2021/10202/) > 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](https://developer.apple.com/videos/play/wwdc2021/10209) > 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](https://developer.apple.com/videos/play/wwdc2021/10204/) > 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](https://developer.apple.com/videos/play/wwdc2021/10210/) > 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](https://developer.apple.com/videos/play/wwdc2021/10134) > 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](https://developer.apple.com/videos/play/wwdc2021/10096/) > 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)](https://developer.apple.com/videos/play/wwdc2018/416/) > 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](https://developer.apple.com/videos/play/wwdc2021/10211/) > 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](https://developer.apple.com/videos/play/wwdc2021/10253/) > 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. > #### Xcode * [How-to: Create compile time reminders in Xcode](https://recoursive.com/2021/09/14/create_compile_time_reminders) > How-to: Create compile time reminders in Xcode * [Minimum requirements and supported SDKs](https://developer.apple.com/support/xcode/#minimum-requirements) * [Convincing Xcode to Map Vim Keys](https://bryce.co/xcode-vim-map) > 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)](https://useyourloaf.com/blog/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. * [Xcode Keyboard Shortcuts](https://useyourloaf.com/blog/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](https://help.apple.com/xcode/#/dev745c5c974) * [Complete reference of every build setting supported for the latest version of Xcode](https://xcodebuildsettings.com) * [Conditional Compilation, Part 1: Precise Feature Flags](https://davedelong.com/blog/2018/07/25/conditional-compilation-in-swift-part-1) * [Conditional Compilation, Part 2: Including and Excluding Source Files](https://davedelong.com/blog/2018/07/25/conditional-compilation-in-swift-part-2) * [Conditional Compilation, Part 3: App Extensions](https://davedelong.com/blog/2019/04/09/conditional-compilation-part-3)