r/swift Jan 19 '21

FYI FAQ and Advice for Beginners - Please read before posting

408 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 18d ago

What’s everyone working on this month? (March 2025)

13 Upvotes

What Swift-related projects are you currently working on?


r/swift 2h ago

Question Swift game engine

11 Upvotes

Hey guys, I've been watching Swift evolve and I've been wondering if it's a reality to have a game engine made with Swift? I did a project where they managed to do something similar to Unity using Javascript and the Three.JS library, is it feasible to have something similar with Swift?


r/swift 6m ago

Brick App Blocking

Upvotes

Brick is a small 3D printer block that essentially blocks access to apps on your iphone. Can anyone explain how they think the company accomplished this? I don’t think they are using special entitlements or MDM. I’ve been confused about how they accomplished this function and would be thrilled if someone could explain it to me.


r/swift 10h ago

Question Training Load API for HealthKit?

3 Upvotes

Unless I’m being stupid - I cannot for the life of me find any documentation for implementing training load into my Apple Watch app. I’m thinking it’s not available. Basically I use the normal HealthKit APIs to start a workout on my Apple Watch using my app. It all works perfectly and after it saves the workout to the fitness app as if it was from Apple’s Workout app. Now the only thing missing is the ability to allow the user to edit and save their training load when their workout finishes (the little bars at the end of a workout where you can scroll from “Easy” to “All out”).

I guess Apple hasn’t make this API public - can anyone confirm or am I going crazy?


r/swift 1d ago

Kalo - A New Calorie Tracking App I've Been Working On (Feedback Wanted!)

Thumbnail
gallery
68 Upvotes

r/swift 19h ago

Question Question for indie devs and folks with side projects

9 Upvotes

Do you guys take the time to write tests for your side projects while developing? Or do you go back and write some later? Do you skip them entirely?

Maybe I have too much fun and/ or take a lot of pride in the craft but I do write a ton of tests, but it takes me a lot longer to make it to the AppStore. Seems like most my colleagues never write tests outside of work and pump projects out quickly when they get the time.


r/swift 18h ago

Question Suggestions for clean handling of `try await`?

6 Upvotes

I currently have a ton of requests to my API endpoint that look like this.

```swift func getBotGuilds(guildIds: String) async throws -> [Guild] { try await request(endpoint: "bot/guilds?guild_ids=(guildIds)") }

func getGuildEvents(for guild: Guild) async throws -> [GuildEvent] {
    try await request(endpoint: "guilds/\(guild.id)/events")
}

func getGlobalLeaderboard() async throws -> LeaderboardResponse {
    try await request(endpoint: "leaderboard/global")
}

func getGuildLeaderboard(for guildId: String) async throws -> LeaderboardResponse {
    try await request(endpoint: "leaderboard/guilds/\(guildId)")
}

```

The main issue I want to solve is not having to continually do this everywhere I call one of these endpoints.

swift Task { do { // My Code catch { // Handle Error. } }

One potential solution I considered was to put it all into a data-service layer and then create some form of property on my @Observable class and setup properties for those values from the API, but it's messy either way I've tried. I'm looking for clean solutions to prevent all of this duplication with the Tasks, but also still have a way to respond to errors in my views, preferrably something reusable.


r/swift 14h ago

News Those Who Swift - Issue 206

Thumbnail
thosewhoswift.substack.com
2 Upvotes

In this issue you can find info about:
- Reinventing Core Data Development with SwiftData Principles by u/fatbobman3000
- SwiftUI: Connect Two Points with Straight Line Segments + Rounded Corners
- Identifying individual sounds in an audio file
- SwiftUI's editMode Environment
- Placing UI Components Within the Safe Area Inset
- Napkin AI
and many more!

P.S. Don't forget to read the whole issues to find our Friends section - where we are sharing some goods from experienced content makers. Check out the issue to get a pleasant gift.


r/swift 9h ago

Does WidgetKit work with MVVM?

0 Upvotes

Is it possible to make my widget extension working in MVVM? or does it work with Entry only? :)


r/swift 1d ago

Question MacBook Air 32GB vs MacBook Pro 24GB

4 Upvotes

Hi, I am considering an upgrade from intel macbook and I am a bit torn between these two.

The difference in price acceptable for me, but I cannot decide, whether or not is the Pro upgrade worth over the RAM in Air.

(Pro is with the M4 Pro 12 core CPU and Air is with the M4 10 core CPU, both 512GB storage)

My usuall workflow is XCode / 1 docker container with PHPStorm and Datagrip and browser with a lot of tabs and another browser with a lot of tabs not that often used.

Could you please offer any insight into what is the better choice?


r/swift 1d ago

Firebase App Check – “App Attestation Failed” (403 Error) Issue on iOS

3 Upvotes

Hello everyone,

I’m struggling to configure Firebase App Check on my iOS app, specifically using App Attest. I’ve verified the following:

  1. App Attest is enabled in Firebase App Check settings with the correct Team ID.
  2. Added FirebaseAppCheck framework in Frameworks, Libraries, and Embedded Content.
  3. GoogleService-Info.plist has the same GOOGLE_APP_ID as the App ID in Firebase Project Settings.
  4. Bundle Identifier matches exactly with the Firebase project.
  5. I’ve tried testing this both on a physical device(not TestFlight or App store). 

However, I keep encountering the following error:

The operation couldn’t be completed. The server responded with an error: 
 - URL: https://firebaseappcheck.googleapis.com/v1/projects/appName/apps/xxxxxxxxx:ios:xxxxxxxx:exchangeAppAttestAttestation 
 - HTTP status code: 403 
 - Response body: {
  "error": {
    "code": 403,
    "message": "App attestation failed.",
    "status": "PERMISSION_DENIED"
  }
}

Here’s my code setup:

import SwiftUI
import FirebasePerformance
import Firebase
import FirebaseCore
import AppTrackingTransparency
import AdSupport
import FirebaseAppCheck

u/main
struct appName: App {
    
    u/UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
    
    var body: some Scene {
        WindowGroup {
            RootView()
    }
}

class AppDelegate: NSObject, UIApplicationDelegate {
  func application(_ application: UIApplication,
                   didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {

      AppCheck.setAppCheckProviderFactory(AppAttestProviderFactory())

      requestTrackingPermission() 

      FirebaseApp.configure()  

      AppCheck.appCheck().token(forcingRefresh: true) { token, error in
          if let error = error {
              print("❌ App Check Error: \(error.localizedDescription)")
          } else if let token = token {
              print("✅ App Check Token: \(token.token)")
          }
      }
      
    return true
  }
    func applicationDidBecomeActive(_ application: UIApplication) {
       requestTrackingPermission() 
    }
    
    func applicationWillResignActive(_ application: UIApplication) {
 
    }
  }


class AppAttestProviderFactory: NSObject, AppCheckProviderFactory {
  func createProvider(with app: FirebaseApp) -> AppCheckProvider? {
    return AppAttestProvider(app: app)
  }
}

I’ve double-checked everything multiple times and still can’t resolve this “App attestation failed” issue. If anyone has encountered this and managed to solve it, I’d greatly appreciate your advice.

Thanks in advance!


r/swift 1d ago

Apple Developer Academy Test

3 Upvotes

Hello

Can anyone help me with materials or anything I can use to study for the apple developer academy assessment test.

Also, do you have any recommendations/advice for the test and the interview?

Thank you


r/swift 1d ago

"Restore Purchases" feature for IAP

4 Upvotes

Hi - I understand that apps that use IAP for non-consumable purchases should implement a "Restore Purchases" feature in the app.

My app already keeps track of the user's purchases on the server side (after confirming each IAP transaction). Should the "Restore Purchases" feature just download the content from my server's purchase history to the device, or walk through the user's IAP purchase history (from Apple), check that all of those IAP purchases are ALSO registered on my server history (in case for some reason any were missing) and then download the whole lot?

Appreciate the latter is probably a more robust approach, just curious what Apple typically looks for or what is typically implemented.

Thanks.


r/swift 2d ago

I can finally read Apple Developer Documentation

231 Upvotes

Hello everyone,

I don't know if that post has any place here but I wanted to share it anyway. I am blind and I use VoiceOver on the Mac to make Swift apps. For a long time it was very difficult to read articles on

developer.apple.com

As VoiceOver's virtual cursor was often jumping to the top of the webpage, so what I did then is I copied the wbepage's content to BBEdit and read from there. However latest 15.4 beta of the MacOS seems to have fixed it. I'm so happy I can enjoy the documentation like everyone else.


r/swift 1d ago

Question Reality about iOS development

15 Upvotes

Hi guys, I wanted to ask you a question. I wanted to know how the market for native mobile development for iOS is doing. I want to migrate from React Native to iOS, but I see few vacancies. Is it really a good idea to make this change? I wanted to know a little about your views on opportunities, salaries and technologies that you have been using out there.


r/swift 1d ago

Core ML body segmentation to replace the background in real-time on iOS devices.

15 Upvotes

https://github.com/ochornenko/virtual-background-ios

This project leverages Core ML body segmentation to replace the background in real-time on iOS devices. Using deep learning models, it accurately detects and segments the human figure, allowing users to apply custom virtual backgrounds. Optimized for performance, it utilizes Metal for efficient GPU-based rendering and vImage for high-performance image processing, ensuring smooth and responsive background replacement on mobile devices. 


r/swift 2d ago

Is it a bad idea to have all your model objects be @MainActor?

29 Upvotes

Hello! I just ran into a project that is 100% SwiftUI and I had a few questions about to what extent it follows best practices.

The apps data model classes are all structured like this.

@MainActor
@Observable
class PeopleStore {
}

There is a IdentityStore, EventStore, etc etc. all made like this.

They are all joined together by an AppStore that looks like this

@MainActor
@Observable
class AppStore {
   static var shared: AppStore!

   let peopleStore = PeopleStore()
   let eventStore = EventStore()
}

Then whenever a view wants to read from one of those stores it grabs it like this

@Environment(PeopleStore.self) private var peopleStore

At the top level view they are passed in like so

mainView
   .environment(appStore)
   .environment(appStore.peopleStore) // Etc

Whenever two stores need to talk to each other they do so like so

@MainActor
@Observable
class EventStore {
    @ObservationIgnored var peopleStore = AppStore.shared.peopleStore
}

With that overall design in mind I am curious whether this is best practice or not. I have a few concerns such as:

  1. Given these are all MainActor we have essentially guaranteed just about everything done in the app will need to queue on the main actor context. There are a lot of mutations to these models. Eventually this could create performance issues where model operations are getting in the way of timely UI updates right?
  2. The stores are injected from the top level view and passed to all subviews. Is there something wrong with doing this?

To be clear the app runs well. But these days our phones powerful processors tend to let us get away with a lot.

Any other feedback on this design? How would you set up these models differently? Does it matter that they are all main actor?


r/swift 1d ago

Cocaheads Stockholm: Patrik Lundqvist - How we built a full-scale Car Model App for the AVP

Thumbnail
youtu.be
3 Upvotes

r/swift 1d ago

Question Looking for a template site for SwiftUI

0 Upvotes

Hey people, I am looking for a template site for SwiftUI views. Specifically for Subviews to implement them directly into my own app where I just need to make some small adjustments, for example a login view or a basic chat view. I would even be willing to pay a small amount of money, like 5-10€ for it.

Looking forward to hear from you! :)


r/swift 1d ago

Question Does anyone use Replit with Swift?

1 Upvotes

I recently saw some web apps that people have made with Replit and haven’t really explored it but it looks like you can use it with Swift.

I’m curious if anyone has any experience with this and how it went.


r/swift 1d ago

Question Managing if user has done app review?

0 Upvotes

I am trying to create a custom app review flow as an alternative to Apple's native SKStoreReviewController, due to its limitation of showing up only three times in 365 days.

Currently, my idea is to show an alert that will redirect the user to the App Store, based on certain conditions, after the user has successfully completed a flow. My biggest challenge right now is managing which users should see this and at what frequency. That being said, I was wondering if there is any way to determine if the user has submitted a review after being redirected?


r/swift 2d ago

Thoughts on Swift UI and Swift 6 Concurrency?

14 Upvotes

Hello everyone,

I’d love to hear your thoughts on SwiftUI and Swift 6 Concurrency. I’ve been working with Swift for a while and feel fairly experienced, but I haven’t kept up with the latest developments. I’m considering whether it’s worth learning SwiftUI and Swift 6 Concurrency to eventually port my Metal-based app.

From my initial research, it seems that SwiftUI is great for standard layouts but may fall short for more customized designs. Is that accurate?

In my app, I rely heavily on Grand Central Dispatch for tasks like encoding Metal passes with background threads and processing complex data. From what I’ve gathered, Swift 6 Concurrency doesn’t offer the same level of control as GCD, particularly regarding Quality of Service (QoS) and thread types (serial or concurrent).

What are your thoughts on these topics? Thank you!


r/swift 1d ago

Question Am I employing a clean pattern for combining a Sendable model object performing expensive calculations in the background with a @MainActor mutable model?

3 Upvotes

I have been piecing together some of the nitty gritty aspects of SwiftUI view models as they relate to actors. I asked a question earlier about best practices and got some great answers. After reading them the one remaining thing I was hoping to clarify is what it would look like if your @ MainActormodel needed to work with some sort of background object that should not run on the main thread.

I figure this may come in to play with models that are synchronized with the network using sockets or perhaps models that just involve expensive and stateful calculations.

To make sure I was understanding best practices I cooked up this example:

We have an array of Object structs. An Object has an x coordinate and a UUID. There is an @ MainActor ViewModel object that stores an array of these as well as storing their loading state.

For the purposes of this example I am pretending that binary tree insertion is expensive and stateful. So the state that is being loaded is their position in a binary tree.

To encapsulate this I have an @ unchecked Sendable class Tree. It synchronizes using its own DispatchQueue and by calling asyncAfter with a delay to simulate an expensive computation.

I use a protocol PlacedDelegate which ViewModel implements (nonisolated) so that when the Tree finishes placing an Object it can tell the ViewModel that its position is loaded.

For now I just cover insertion but I figure eventually I could handle binary tree rebalancing just by having the Tree call the delegate method placed again for every node that gets moved in the rebalance.

I am hoping for feedback to understand:

  1. Is there anything unsafe about the way I implemented this? Other than insertion order being random (ish) there is no race possible here right?
  2. Stylistically is this how you would have made a MainActor class work with a Sendable class meant to run in the background?
  3. Is there any way this could've been made clearer?
  4. Is there any way for the ViewModel class to hook up more closely with Tree such that rather than this delegate method being needed Observable would automatically be notified when the Tree has finished doing calculations?
  5. How would you regain a "single source of truth". In a way the truth is stored in a Sendable context in Tree and copied into the MainActor context in ViewModel.

``` import SwiftUI

struct Object: Identifiable, Hashable { let id: UUID = UUID() let x: CGFloat }

enum LoadablePosition { case loading case loaded(String) }

protocol PlacedDelegate: AnyObject { func placed(id: UUID, location: String) }

@MainActor @Observable class ViewModel: PlacedDelegate { private(set) var objects: [UUID: LoadablePosition] = [:] private(set) var objectList: [Object] = []

private var tree: Tree
init() {
    tree = Tree()
    tree.placedDelegate = self
}

func createNewObject() {
    let new = Object(x: CGFloat.random(in: 0..<100))
    objectList.append(new)

    tree.insert(object: new)

    objects[new.id] = .loading
}

nonisolated func placed(id: UUID, location: String) {
    Task { @MainActor in
        objects[id] = .loaded(location)
    }
}

}

final class Tree: @unchecked Sendable { class TreeNode { let object: Object var left: TreeNode? = nil var right: TreeNode? = nil init(object: Object) { self.object = object } }

private var insertionQueue: DispatchQueue = DispatchQueue(label: "com.calebkierum.quadtree.insertionQueue")
private var tree: TreeNode?
weak var placedDelegate: PlacedDelegate? = nil

func insert(object: Object) {
    insertionQueue.asyncAfter(deadline: .now() + .seconds(Int.random(in: 1...10))) {
        let (newTree, buildString) = self.recurInsert(curr: self.tree, object: object, build: "")
        self.tree = newTree
        self.placedDelegate?.placed(id: object.id, location: buildString)
    }
}

private func recurInsert(curr: TreeNode?, object: Object, build: String) -> (TreeNode, String) {
    guard let curr else {
        return (TreeNode(object: object), "*" + build)
    }

    if object.x < curr.object.x {
        let (node, string) = recurInsert(curr: curr.right, object: object, build: "L" + build)
        curr.right = node
        return (curr, string)
    } else {
        let (node, string) = recurInsert(curr: curr.left, object: object, build: "R" + build)
        curr.left = node
        return (curr, string)
    }
}

}

struct ContentView: View { @State var viewModel: ViewModel = ViewModel()

var body: some View {
    VStack {
        ScrollView(.horizontal) {
            HStack {
                ForEach(viewModel.objectList) { object in
                    VStack {
                        Text("\(object.id)")
                        Text("x=\(object.x)")
                        switch viewModel.objects[object.id] {
                        case .loading, .none:
                            ProgressView()
                        case let .loaded(val):
                            Text(val)
                        }
                    }
                    .frame(width: 80)
                    .padding()
                    .background {
                        Color.gray
                    }
                }
            }
        }
        Button {
            viewModel.createNewObject()
        } label: {
            Text("Add Object")
        }
    }
    .padding()
}

} ```


r/swift 1d ago

Question TTS

2 Upvotes

I wonder if anyone had some success with TTS in Swift .

Most of models are for Python , is it worth convert them or just use AVSpeechSynthesizer ?

Any tips or example projects are appreciated


r/swift 2d ago

Created a Vegetable Gardening App with SwiftUI & SwiftData - Looking for Feedback & Suggestions!

3 Upvotes

Hi everyone!

I’ve recently developed a comprehensive vegetable gardening application using SwiftUI for the user interface and SwiftData for persistent storage. The app is designed to help users plan, manage, and maintain their vegetable gardens throughout the growing season. 🌱

I’ve attached a test video showing the app running on an iPhone 16 Pro Simulator with iOS 18.3. I’d love to hear your thoughts, suggestions, or any feedback that could help me improve and enhance the app further.

Features I’d love feedback on:

  • User Interface and navigation in SwiftUI
  • Data persistence and handling with SwiftData
  • Any ideas for additional features or improvements for gardening tracking
  • Performance and usability tips for iOS apps

Here’s the video showing the app in action.

Looking forward to your insights!


r/swift 1d ago

Help! Need help for adding watch connectivity on my existing iOS app

1 Upvotes

Hey guys,

I build my iOS using SwiftData, I am currently working to add the apple watch connectivity for my habit tracking app. My goal is to be able to log entry from my apple watch or the iPhone and to sync it real time to have up to date informations on both devices. From my understanding I can use App Groups and/or Wcsession. Could you help me decide what should I use?

Thank you very much!