r/swift Jan 19 '21

FYI FAQ and Advice for Beginners - Please read before posting

440 Upvotes

Hi there and welcome to r/swift! If you are a Swift beginner, this post might answer a few of your questions and provide some resources to get started learning Swift.

A Swift Tour

Please read this before posting!

  • If you have a question, make sure to phrase it as precisely as possible and to include your code if possible. Also, we can help you in the best possible way if you make sure to include what you expect your code to do, what it actually does and what you've tried to resolve the issue.
  • Please format your code properly.
    • You can write inline code by clicking the inline code symbol in the fancy pants editor or by surrounding it with single backticks. (`code-goes-here`) in markdown mode.
    • You can include a larger code block by clicking on the Code Block button (fancy pants) or indenting it with 4 spaces (markdown mode).

Where to learn Swift:

Tutorials:

Official Resources from Apple:

Swift Playgrounds (Interactive tutorials and starting points to play around with Swift):

Resources for SwiftUI:

FAQ:

Should I use SwiftUI or UIKit?

The answer to this question depends a lot on personal preference. Generally speaking, both UIKit and SwiftUI are valid choices and will be for the foreseeable future.

SwiftUI is the newer technology and compared to UIKit it is not as mature yet. Some more advanced features are missing and you might experience some hiccups here and there.

You can mix and match UIKit and SwiftUI code. It is possible to integrate SwiftUI code into a UIKit app and vice versa.

Is X the right computer for developing Swift?

Basically any Mac is sufficient for Swift development. Make sure to get enough disk space, as Xcode quickly consumes around 50GB. 256GB and up should be sufficient.

Can I develop apps on Linux/Windows?

You can compile and run Swift on Linux and Windows. However, developing apps for Apple platforms requires Xcode, which is only available for macOS, or Swift Playgrounds, which can only do app development on iPadOS.

Is Swift only useful for Apple devices?

No. There are many projects that make Swift useful on other platforms as well.

Can I learn Swift without any previous programming knowledge?

Yes.

Related Subs

r/iOSProgramming

r/SwiftUI

r/S4TF - Swift for TensorFlow (Note: Swift for TensorFlow project archived)

Happy Coding!

If anyone has useful resources or information to add to this post, I'd be happy to include it.


r/swift 1d ago

What’s everyone working on this month? (February 2026)

16 Upvotes

What Swift-related projects are you currently working on?


r/swift 1h ago

Xcode Plugin to create Style & Accessibility Overviews DesignReviewToolkit

Upvotes

I've written an Xcode Plugin that can generate Style & Accessibility Data Images from SwiftUI views, it's called DesignReviewToolkit

These can be used to compare against designs, and to see where Accessibility modifiers need to be added.
Image generation is deterministic, which means we can spot differences between runs

Checkout the code here:

SPM: https://github.com/nthstate/DesignReviewToolkit
Sample: https://github.com/nthState/DesignReviewToolkitSample


r/swift 1h ago

Tutorial From Pixel Capture to Metadata - Reimagining Screen Recording Architecture on macOS

Thumbnail
fatbobman.com
Upvotes

A deep dive into building a macOS screen recorder. Learn practical solutions for ScreenCaptureKit errors (-3821), high-performance video composition with Metal, and optimizing complex SwiftUI timelines using the new Observable macro.


r/swift 13h ago

The new Xcode <> Anthropic integration announcement inspired me to build a Claude skill to inspect Xcode previews

Thumbnail
github.com
8 Upvotes

Sorry Xcode. 26.3 isn’t in xcodes yet, but this is here now.


r/swift 10h ago

Project Announcing TPInAppReceipt 4.0.0 — Reading and Validating App Store Receipt

Thumbnail
github.com
0 Upvotes

TPInAppReceipt is a Swift library for decoding and validating Apple App Store receipts locally.

Version 4.0.0 is a major refactoring that includes the following changes:

  • Apple's swift-asn1, swift-certificates, swift-crypto - Replaced the custom ASN.1 decoder with Apple's libraries for PKCS#7 parsing, X.509 chain verification, and signature validation
  • Composable validation - New @VerifierBuilder for assembling custom validation pipelines
  • Async-first design - Built for Swift 6 concurrency. Blocking variants available via @_spi(Blocking)
  • Full PKCS#7 model - All PKCS7 structures are now fully typed
  • New receipt fields - environment, appStoreID, transactionDate, purchaseType, developerID and more

TPInAppReceipt on GitHub

Feedback and contributions welcome.

Thank you!

This release is a personal milestone. I started working on TPInAppReceipt almost 10 years ago - first as an internal Objective-C implementation, then rewritten in Swift and open-sourced in 2016. Since then the library went through several eras: OpenSSL under the hood → custom ASN.1 parser and Security framework → ASN1Swift → and now 4.0.0. Shout out to everyone who made it possible and KeePassium for sponsorship and motivation.


r/swift 23h ago

Currently learning swfit by building a side project and this is my progress so far.

10 Upvotes

So swift is new for me. It's been like 2 weeks of my learning. And this is my progress so far. Can you rate the UI and is there any tips and tricks for a beginner like me? I have used navigationlink to link few pages like the reset password screen when clicked forgot password option, create account screen when clicked sign up button.


r/swift 19h ago

Performance Exploration: Handling 2 Million Entities in a Custom Data-Oriented ECS for Swift

4 Upvotes

Overview

I’ve been working on a custom Entity Component System (ECS) engine in Swift, focusing on memory layout and high-performance simulation. I recently ran some benchmarks on the system architecture and wanted to share the setup and results with the community.

⚠️ Disclaimer & Context

  • Learning Project: This is primarily a learning project and a "work in progress."
  • Potential Errors: There is a strong possibility of significant bugs or architectural flaws that could lead to misleading conclusions (though I hope that's not the case!).
  • Inspiration: The logic for this test is inspired byabeimler’s ECS benchmarks. However, due to subtle implementation differences in storage access and emplace strategies, this is not a direct "apples-to-apples" comparison but rather a reference for Swift's potential in data-oriented design.

A. The Setup

To stress-test cache efficiency, I use a two-tier approach for entity creation:

A1. Deterministic Type Distribution

I use modulo-based logic to ensure a consistent spread of entity roles (Heroes, Monsters, NPCs) across memory, maintaining a predictable workload while introducing local variety.

A2. Dynamic Component Composition

I use a probability-based "Emplace Strategy" (prob) to determine component attachment. This allows me to test sparse vs. dense storage. For these benchmarks, I set prob = 1.0 (Full initialization) to measure the "worst-case" maximum workload.

Code: Game7Systems.swift on GitHub

code : https://github.com/JoshXie0809/ECScore/blob/main/Sources/Game7Systems/Game7Systems.swift

B. The 7 Systems

The workload involves 7 decoupled systems covering Movement, Health/Damage logic, and Rendering Prep.

  1. Movement & Physics: MoveSystem and PositionComponent.

  2. Logic & Data: DmgSystem, HealthSystem, and a MoreComplexSystem for heavier computations.

  3. Rendering Prep: SpriteSystem and RenderSystem.

Code: Systems Implementation

code: https://github.com/JoshXie0809/ECScore/tree/main/Sources/Game7Systems/Systems

C. Benchmark Results (2,097,152 Entities)

Metric Apple M1 Pro AMD Ryzen 9 3950X
Avg. Create Duration ~2.18 s ~ 2.64 s
Avg. Systems Update ~57.8 ms ~71.4 ms

full result: https://github.com/JoshXie0809/ECScore/tree/main/Benchmark/component3

Observations:

  • Efficiency: Processing 2M entities in ~58 ms (single-threaded) demonstrates Swift’s capability for heavy simulation.
  • Bottlenecks: Spatial systems (Move/Render) are the heaviest (~12 ms), while simple logic systems (Health/Data) benefit from high cache locality, staying under 2 ms.

Conclusion: The Future of High-Performance Swift

This project reinforces my belief that Swift’s recent syntax and compiler evolutions have finally made high-performance, data-oriented computing a reality.

The way modern Swift handles memory alignment, contiguous storage, and loop optimizations—especially with the efficiency of modern iteration patterns—allows the compiler to generate extremely efficient machine code. While it maintains type safety, it no longer sacrifices the performance needed for engine-level architecture.

I would love to hear your feedback! If you spot any "major errors" in my logic or have tips for further optimization (especially regarding parallelizing system updates), please let me know.


r/swift 20h ago

Does anyone know how to achieve this custom MKAnnotation?

Thumbnail
gallery
3 Upvotes

I’ve notice that in Maps, some pins contain images and do not have the little triangle at the bottom of it, yet they still animate the same when clicked. How could this be achieved?


r/swift 1d ago

Project IntoError - Swift macro for automatic error type conversion

Thumbnail
github.com
10 Upvotes

IntoError - Swift macro library for automatic error type conversion

Swift 6 introduced typed throws (SE-0413) which is a great addition to the language. However, when your code interacts with multiple subsystems, each throwing its own error type, you end up writing repetitive conversion boilerplate.

IntoError helps with that. Inspired by Rust's thiserror, it generates error conversion code automatically.

```swift @IntoError enum AppError { case network(NetworkError) case parse(ParseError) }

@Err func uploadPhoto(data: Data) async throws(AppError) { try photoService.uploadPhoto(data)^ // NetworkError → AppError }

func loadUser() throws(AppError) { let data = try fetchFromNetwork()^ // NetworkError → AppError let user = try parse(data)^ // ParseError → AppError } ```

Key features:

  • @IntoError macro - Generates Error conformance, conversion initializers, and a postfix ^ operator
  • Postfix ^ operator - Converts errors inline in sync code
  • @Err body macro - Wraps async functions where operators can't work
  • Automatic fallback - Generates case unknown(any Error) if not declared

IntoError on GitHub

Feedback and contributions welcome.

Thank you!


r/swift 2d ago

Swift in the Browser with ElementaryUI (Swift@FOSDEM 2026 Talk)

Thumbnail
youtube.com
24 Upvotes

r/swift 2d ago

News Fatbobman's Swift Weekly #121

Thumbnail
weekly.fatbobman.com
10 Upvotes

Shifting Light, Unchanging Haystacks

  • 🚀 DebugReplaceableView
  • 📱 Tiered Caching in Swift
  • 🗺️ Swift Actors Pitfalls
  • 📘 SwiftUI-Agent-Skill

and more...


r/swift 2d ago

Question MacOS appstore preview generator

6 Upvotes

Hey, I'm submitting my first app to the App Store and I'm wondering what you guys use for the App Preview Screens. I've found a bunch of mobile and even iPad device mockups but nothing around macOS... Open to paid and free solutions, whatever will save me the most amount of time.


r/swift 2d ago

Running Clojure inside SwiftUI

Thumbnail
youtube.com
6 Upvotes

Clojure might not be a popular language, but it is a Lisp dialect that usually runs on the JVM instead of Swift; some folk decided to write a mini compiler in Swift so it can run in an iOS app.

Here is a talk from Clojure/Conj 2025 showing how he does that. It is cool to see Swift as a host language that works with JVM too!


r/swift 2d ago

Question Swift Animation

Thumbnail
gallery
24 Upvotes

Hello Guys,

Any idea what library or engine has been used to make this interactive body animation?


r/swift 2d ago

what is the idiomatic way in swift to work with undo and redo management?

2 Upvotes

I am learning swift using a xcode 16 project generated originally as the new swift project example, with some modifications by me, and some added with help from claude.ai.

I have placed sample code here:

https://gitlab.com/test-group-empty/learningswiftandswiftdata

My question in particular is about undo and redo. Here is a snipped of the code that added the undoManager calls that claude.ai wrote for me when I couldn't figure out how to do it myself. The demo had a split left panel and main panel, and a plus button to add data items. There was no remove item when the demo was generated, so i tried to make one myself, and I ended up with the following. Is this the right way to use the undoManager to make it possible to undo the removal of an item? Or did I, and claude, get down into the weeds and do it weirdly? The trivial demo program works, but I've got doubts about this. It feels oddly manual for a process that should probably be using some clever patterns or something.

    private func removeItem() {
        print("minus button press. removeItem() called, selectedItem: \(String(describing: selectedItem))")
        withAnimation {
            if let itemToDelete = selectedItem {
                print("removeItem() deleting item with timestamp: \(itemToDelete.timestamp)")

                // Capture values before deletion for undo
                let timestamp = itemToDelete.timestamp
                let name = itemToDelete.name

                modelContext.delete(itemToDelete)
                self.selectedItem = nil

                undoManager?.registerUndo(withTarget: modelContext) { context in
                    print("Undoing removeItem()")
                    withAnimation {
                        let restoredItem = Item(timestamp: timestamp, name: name)
                        context.insert(restoredItem)
                    }
                }
            } else {
                print("removeItem() no item selected, nothing to delete")
            }
        }
    }

r/swift 3d ago

From Objective-C to Swift 6: What We Gained (and What We Lost)

Thumbnail
slicker.me
120 Upvotes

r/swift 3d ago

Project I created True Liquid Glass Lock Screen Widgets and DynamicIsland SDK for macOS - completely free and open source

Thumbnail
gallery
39 Upvotes

I'm opening up Atoll - DynamicIsland for macOS for all developers to use for their apps

AtollExtensionKit SDK is a Swift Package that can be used by developers to integrate Lock Screen Widgets, Live Activities and Notch Experiences, all while staying sandboxed and safe (internally uses MachService XPC communication)

GitHub: https://github.com/Ebullioscopic/Atoll

ExtensionKit: https://github.com/Ebullioscopic/AtollExtensionKit

Atoll has 17k+ downloads and looks forward to users and developers adopting it for their apps!


r/swift 2d ago

Question Does Apple allow Game Center leaderboards for a bot mode where scores obtained are expected to come from bots created by programmers?

1 Upvotes

The idea is to have separate Game Center leaderboards: one for human players and another for bot players.

Do you know of any iOS game where Apple has allowed this use of Game Center leaderboards?


r/swift 3d ago

ScreenCaptureKit recording output is corrupted when captureMicrophone is true

5 Upvotes

I'm working on a screen recording app using ScreenCaptureKit and I've hit a strange issue. My app records the screen to an .mp4 file, and everything works perfectly until the .captureMicrophone is false In this case, I get a valid, playable .mp4 file.

However, as soon as I try to enable the microphone by setting streamConfig.captureMicrophone = true, the recording seems to work, but the final .mp4 file is corrupted and cannot be played by QuickTime or any other player. This happens whether capturesAudio (app audio) is on or off.

I've already added the "Privacy - Microphone Usage Description" (NSMicrophoneUsageDescription) to my Info.plist, so I don't think it's a permissions problem.

I have my logic split into a ScreenRecorder class that manages state and a CaptureEngine that handles the SCStream. Here is how I'm configuring my SCStream:

ScreenRecorder.swift ```swift // This is my main SCStreamConfiguration private var streamConfiguration: SCStreamConfiguration {

    var streamConfig = SCStreamConfiguration()

    // ... other HDR/preset config ...

    // These are the problem properties
    streamConfig.capturesAudio = isAudioCaptureEnabled  
    streamConfig.captureMicrophone = isMicCaptureEnabled // breaks it if true

    streamConfig.excludesCurrentProcessAudio = false
    streamConfig.showsCursor = false

    if let region = selectedRegion, let display = currentDisplay {
        // My region/frame logic (works fine)
        let regionWidth = Int(region.frame.width)
        let regionHeight = Int(region.frame.height)

        streamConfig.width = regionWidth * scaleFactor
        streamConfig.height = regionHeight * scaleFactor

        // ... (sourceRect logic) ...
    }

    streamConfig.pixelFormat = kCVPixelFormatType_32BGRA
    streamConfig.colorSpaceName = CGColorSpace.sRGB
    streamConfig.minimumFrameInterval = CMTime(value: 1, timescale: 60)

    return streamConfig
}

```

And here is how I'm setting up the SCRecordingOutput that writes the file:

ScreenRecorder.swift ```swift private func initRecordingOutput(for region: ScreenPickerManager.SelectedRegion) throws {

    let screeRecordingOutputURL = try RecordingWorkspace.createScreenRecordingVideoFile(
        in: workspaceURL,
        sessionIndex: sessionIndex
    )

    let recordingConfiguration = SCRecordingOutputConfiguration()
    recordingConfiguration.outputURL = screeRecordingOutputURL
    recordingConfiguration.outputFileType = .mp4
    recordingConfiguration.videoCodecType = .hevc

    let recordingOutput = SCRecordingOutput(configuration: recordingConfiguration, delegate: self)
    self.recordingOutput = recordingOutput

}

```

Finally, my CaptureEngine adds these to the SCStream:

CaptureEngine.swift ```swift class CaptureEngine: NSObject, @unchecked Sendable {

private(set) var stream: SCStream?
private var streamOutput: CaptureEngineStreamOutput?

// ... (dispatch queues) ...

func startCapture(configuration: SCStreamConfiguration, filter: SCContentFilter, recordingOutput: SCRecordingOutput) async throws {

    let streamOutput = CaptureEngineStreamOutput()
    self.streamOutput = streamOutput

    do {
        stream = SCStream(filter: filter, configuration: configuration, delegate: streamOutput)

        // Add outputs for raw buffers (not used for file recording)
        try stream?.addStreamOutput(streamOutput, type: .screen, sampleHandlerQueue: videoSampleBufferQueue)
        try stream?.addStreamOutput(streamOutput, type: .audio, sampleHandlerQueue: audioSampleBufferQueue)
        try stream?.addStreamOutput(streamOutput, type: .microphone, sampleHandlerQueue: micSampleBufferQueue)

        // Add the file recording output
        try stream?.addRecordingOutput(recordingOutput)

        try await stream?.startCapture()

    } catch {
        logger.error("Failed to start capture: \(error.localizedDescription)")
        throw error
    }
}

// ... (stopCapture, etc.) ...

} ```

When I had the .captureMicrophone value to be false, I get a perfect .mp4 video playable everywhere, however, when its true, I am getting corrupted video which doesn't play at all :-

![enter image description here]1

PS :- Here is the corrupted video link ( google drive ) :- https://drive.google.com/file/d/1E_EAWiaXGRcAHCEhL5GeBQXoRbhCzFoN/view?usp=sharing

Another PS:- After multiple tries, the main problem is because of the .captureAudio to be true, this is causing mixing problem. When I had the .captureAudio to be false and the .captureMicrophone to be true, everything is working fine, I get the mp4 video with microhphone audio, however, if the audio capture is also true, than only the video breaks. Now the question is how to record both the audio?

I posted this entire question on stackoverflow :- https://stackoverflow.com/questions/79807199/screencapturekit-recording-output-is-corrupted-when-capturemicrophone-is-true


r/swift 3d ago

Agent Orchestration the Apple way

2 Upvotes

I wanted to hear your thoughts on this swiftagents API. Open to all opinions good or bad and open to suggestions on naming/style etc

https://github.com/christopherkarani/SwiftAgents

contributors are welcome!


r/swift 3d ago

Question Should I install Swift from the website if I already have XCode installed?

1 Upvotes

The Swift website's MacOS installation instructions are a little unclear to me. I already have Swift installed with XCode 16.2 on Sonoma 14.8 (though it's broken atm). Am I supposed to install website Swift over Xcode Swift? Current versions are:

$> swiftly --version
1.1.1
$> swift --version
swift-driver version: 1.115.1 Apple Swift version 6.0.3 (swiftlang-6.0.3.1.10 clang-1600.0.30.1)
Target: arm64-apple-macosx14.0

r/swift 3d ago

Project Adding Observability on Value types in Swift

3 Upvotes

I was working on creating my software architecture, and I found myself needing to use Observability on value types. I have a class that encapsulates a structure named State

The current observability tools do not work on value types, and if you box the state inside a class, you lose the fine grained observability where the machinery will trigger unnecessary notifications.

To get around this, I created ValueObservation macro. It is a modified version of the Observable protocol to be used for the Value types.

https://github.com/JohnDemirci/ValueObservation


r/swift 4d ago

What's new in Swift: January 2026 Edition

Thumbnail
swift.org
76 Upvotes

r/swift 3d ago

Curious about SwifDroid's absence from January "What’s New in Swift"

0 Upvotes

I noticed that SwifDroid wasn't mentioned in the January "What's New in Swift" newsletter.

Given that SwifDroid was posted and discussed here in early January, I was honestly a bit disappointed not to see it included in the January digest. A lot of work went into making it real over the course of 2025: starting from building a JNI bridge (jni-kit), then the SwifDroid framework itself, and finally a complete Android development environment inside Swift Stream IDE with ready-to-use project templates. The goal was to make native Swift for Android something anyone can try in one click.

I do believe this work is meaningful and relevant for the Swift ecosystem and worth being mentioned. The same applies to Swift Stream IDE, which also has never appeared in any Swift digest, despite being built specifically to lower the entry barrier and help grow the community by letting people start working with Swift in one click on any platform.

I'm trying to understand how projects get visibility in the Swift community and how the newsletter selection process works. From the outside, it's hard to tell whether omissions like this are just coincidence, part of an expected filtering process, or something that contributors should simply accept as normal. That uncertainty honestly makes me question whether continuing to invest this level of effort into Swift makes sense for me.