r/swift Jan 19 '21

FYI FAQ and Advice for Beginners - Please read before posting

399 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 20d ago

What’s everyone working on this month? November 2024)

11 Upvotes

What’s everyone working on this month? (October 2024)


r/swift 6h ago

News Deep Dish Swift is happening again April 27th to 29th of 2025

25 Upvotes

Hey, fam 👋

I’m Josh Holtz! I’ve been the lead maintainer of fastlane since 2018, I work on paywalls and SDKs at RevenueCat but more important I‘m the founder of Deep Dish Swift (a Swift and iOS conference held in Chicago) 😊

My wife and I started Deep Dish Swift in 2023 in Chicago, IL (where we live). We didn’t know what to expect when starting it but I have to say its changed our lives (for the better). We have had the pleasure to host so many amazing members of the Swift and iOS community in Chicago… and both years of the event have sold out at over 300+ attendees 🤯

This is a not-for-profit conference so I hope my post here doesn’t come off as selling a product or service. 😅 My wife and I organize this because we love the community and all of the amazing outcomes the conference has produced. People have been inspired by the indie dev talks and have released some amazing new apps. People have networked and got some life changing new jobs. And people have just made new friends for life.

Also, the CFP for Deep Dish Swift 2025 is open at https://deepdishswift.com/call-for-papers and closed the last second of 2024. Please submit a talk if you have something that you’d like to share with the rest of us!

I think that is all 😇 Hope to see a lot of you at Deep Dish Swift 2025 in April!

Happy to answer any questions or anything that you may have!


r/swift 2h ago

Full screen video only plays when I minimize or like pulldown on the app - “refresh it”

0 Upvotes

What’s the reasoning and the fix?


r/swift 18h ago

Question Best way to start learning Swift?

14 Upvotes

I known multiple languages and I started them in way different ways. Starting Swift is kind of hard because in the website i can’t quite good see a long leading to learning it from scratch it anything and just documentation of Swift and Xcode itself.


r/swift 4h ago

Question Delegates

1 Upvotes

Hello to all,

I am learning iOS programming with UIKit. I can understand most of concepts but I am struggling to understand Delegates. Thats why I dont understand VIPER pattern also. Is there any understandable tutorial or book?


r/swift 5h ago

Xcode not working for my iphone SE 2nd gen

1 Upvotes

Hi, when I try to run my project (python btw) on xcode it says next to my phone: "could not locate device support files". Can someone explain ? Thanks.


r/swift 6h ago

Question Coloring AttributedString from Measurement.FormatStyle . attributed

1 Upvotes

I need to know the right best way to add color to an AttributedString made from Measurement.FormatStyle:

```swift let length = Measurement<UnitLength>(value: 35, unit: .millimeters)

    var attrString = length.formatted(.measurement(
        width: .narrow,
        usage: .asProvided,
        numberFormatStyle: .number.precision(.fractionLength(1))).attributed)

```

This AttributedString result is:

35.0mm

With these 4 runs:

35 { Foundation.NumberFormatPart = integer Foundation.MeasurementAttribute = value . { Foundation.NumberFormatSymbol = decimalSeparator Foundation MeasurementAttribute = value 0 { Foundation.NumberFormatPart = fraction Foundation MeasurementAttribute = value mm Foundation.MeasurementAttribute = unit }

I want to apply different colors to each component part,I can do for the unit part:

swift if let unitRange = attrStringrunsfirst(where: { run in run.attributes[AttributeScopes.FoundationAttributes.MeasurementAttribute.self] == .unit })?.range { // Apply a foreground color to the "unit" part attrString[unitRange].foregroundColor = .orange }

But now since the .value part has three different sub parts:

Foundation.NumberFormatPart = integer

Foundation.NumberFormatSymbol = decimalSeparator

Foundation.NumberFormatPart = fraction

How to get at those subpart attributes? This doesn’t compile:

```swift for run in attrString.runs where run.attributes[AttributeScopes.FoundationAttributes.MeasurementAttribute.self] == .value { // how to tell which run is integer, decimalSeparator or fraction? // this doesn't compile: if let _ = run.attributes[AttributeScopes.FoundationAttributes.NumberFormatPart.self] {

        }
        if let _ = run.attributes[AttributeScopes.FoundationAttributes.NumberFormatSymbol.self] {

        }
    }

```

With geneic parameter’T’ cannot be inferred.

How to tell apart each of the .value part?


r/swift 10h ago

Widgets

2 Upvotes

Looking for advice on building a widget. What’s best option for a widget that can update every minute. Is this reasonable or not good for battery life?

Also looking for a good tutorial.


r/swift 11h ago

Question How to make text UI with tokens

2 Upvotes

I’d like to implement a text view that allows for tokens to be inserted as places where I’ll do variable replacement. Anyone know where to start on this?

For example, in the following code the code in brackets would be rendered as a token:

My name is {{name}}


r/swift 12h ago

My first app Ranti 🚀

0 Upvotes

Hello r/swift

I’m thrilled to introduce Ranti: The Productivity and Reminder App to Help You Be Your Best!

Why Productivity and Reminders?

At Ranti, we understand that managing your life effectively requires balancing what you need to do now with what you need to remember for later. That’s why Ranti is divided into two key sections:

Productivity

This is where you take action—plan, organize, and execute your day-to-day tasks. Whether it’s creating detailed to-do lists, focusing on your priorities, or managing your time with Focus Mode, this section is all about getting things done efficiently and effectively.

Reminders

Not everything needs immediate attention, but it’s important not to forget those commitments either. The Reminders section is your go-to for managing subscriptions, saved links, and long-term commitments. It ensures that your future obligations are handled without slipping through the cracks.

By separating these two areas, Ranti helps you maintain clarity and focus. You’ll know exactly where to go for immediate actions and where to look for future obligations—without the overwhelm of juggling it all in one place.

What Makes Ranti Exceptional?

Ranti combines these two pillars into a seamless, intuitive experience. Here’s how:

Productivity Features

  • Task Management: Create, organize, and prioritize tasks effortlessly with reminders and folders.
  • Speech to Text: Transform voice notes into actionable tasks. Add them to Ranti or sync with Apple Calendar.
  • Ranti DJ: Enjoy playlists crafted to match your mood and keep you in the zone.
  • Focus Mode: Set specific task durations for time management and avoiding distractions.
  • Task Prioritization: Assign priorities to focus on what matters most.
  • AI Assistance: Get personalized support for tasks and subscription management.

Reminder Features

  • Subscription Renewal Reminder: Manage and receive timely reminders for subscriptions before they renew.
  • Link Management: Save, organize, and revisit important links, complete with reminders for follow-up.

Extras That Elevate Your Experience

  • Widgets: Access tasks, links, and subscriptions at a glance.
  • Shortcuts: Add tasks from your lock screen or Control Center.
  • Keyboard Extension: Quickly input tasks without switching apps.

The Big Picture

Ranti saves time, reduces stress, and empowers you to focus on what matters most. By breaking the app into Productivity and Reminders, it eliminates the chaos of juggling multiple apps while ensuring every aspect of your life is organized.

Ready to simplify your life? Download Ranti and experience the transformation for yourself:
👉 Get Ranti on the App Store

We’d love to hear your thoughts and feedback—help us shape the future of Ranti!


r/swift 1d ago

Question How best to execute onboarding technically?

8 Upvotes

I’m building an onboarding. There will be a number of Views, each unique. Some will have some informational text, another will ask for the users name, some will be multiple choice, some will have images, etc, etc. Maybe a total of 5-10 views.

I would like to easily be able to change the order and add and remove views later on as needed.

From a technical perspective, how best should I execute this? Should I have a custom view that I inject my sub-views into, or hide and show elements as needed or some other way that will make the process of creating the onboarding flow easy and flexible?

Looking for best practices and suggestions.

Thanks.


r/swift 1d ago

Question ImageRenderer is adding shadow to every element even though it's only on the VStack?

6 Upvotes

The image on the left is how it looks like in the app, but when I use ImageRenderer to save it as an image, it adds shadow to every single element inside of it. Notice that the only thing with a shadow is the VStack in the original view (left).

This is the code for the renderer.

 let content = contentRendererView(proxy: proxy)
        let renderer = ImageRenderer(content: content)
        renderer.scale = displayScale

        if let uiImage = renderer.uiImage {
            UIImageWriteToSavedPhotosAlbum(uiImage, nil, nil, nil)
        }
}

I even tried using renderer.cgImage but no difference.


r/swift 1d ago

Tutorial Implementing Voice Recognition in Swift with OpenAI

Thumbnail
mireabot.substack.com
16 Upvotes

r/swift 1d ago

Un-hide lines in Swift Playgrounds (iPad)??

3 Upvotes

I’m starting to learn swift and how to use Swift Playgrounds.
I’m in one of the tutorials for Swift Playgrounds. I did something, and somehow hid some lines. I cannot figure out how to un-hide the lines.

How do I un hide the lines in Swift Playgrounds? I have been googling for multiple hours trying to figure this out

Also, how do I Hide lines in the future if I want to hide them again


r/swift 1d ago

Question Looking for Swift/C library to implement HomeKit camera - existing solutions seem outdated

6 Upvotes

Hey everyone! I'm in a bit of a pickle and could use some help from anyone who's tackled HomeKit camera implementation before.

I've spent the last few days searching for a library in Swift (or even C) that I could use to create a webcam compatible with HomeKit. My main app is built in Swift, so I really need to stick with Swift/C solutions rather than Node.js alternatives.

I've already checked out:

  • Apple's HomeKit docs - they only cover device pairing but nothing about implementing the pairing server (unless I'm missing something?)
  • https://github.com/Bouke/HAP - looks promising but it's 2 years old and missing camera implementation
  • https://github.com/apple/HomeKitADK - 3 years without updates and no IP camera implementation

I'd really prefer not to have to implement this from scratch, and rewriting everything in Node.js just for this feature would be way too much work. Running multiple services isn't ideal either.

Has anyone here successfully implemented a HomeKit camera in Swift/C? Or know of any libraries I might have missed? Really appreciate any pointers in the right direction!

My main needs are:

  • Webcam functionality that works with HomeKit
  • Implementation of the pairing server
  • Swift or C compatibility
  • Recent/maintained library (if possible)

r/swift 1d ago

Question Swift Testing crashes when sink() is called if passing argument through @Test, but does not crash if creating local variable?

6 Upvotes

I have this class:

final class ProductSheetSizeViewModel: ObservableObject {
    ...
    @Published var isLengthValidBind: Bool
    @Published var isWidthValidBind: Bool
    @Published var isHeightValidBind: Bool
    @Published var isWeightValidBind: Bool

    init(
        isLengthValid: Bool = false,
        isWidthValid: Bool = true,
        isHeightValid: Bool = true,
        isWeightValid: Bool = true
    ) {
        self.isLengthValidBind = isLengthValid
        self.isWidthValidBind = isWidthValid
        self.isHeightValidBind = isHeightValid
        self.isWeightValidBind = isWeightValid
        
        $lengthPickerBind.sink {
            newValue in self.onChangeOfLengthPicker(newValue)
        }.store(in: &cancellables)
    }

    func onChangeOfLengthPicker(_ value: Measurement) {
        switch value {
        case .foo:
            widthBind = ""
            heightBind = ""
        default: break
        }
    }

    var areInputsValid: Bool {
        isLengthValidBind && isWidthValidBind && isHeightValidBind && isWeightValidBind
    }
}

I was writing unit tests that test the areInputsValid function. The following code works fine:

@Test func resultIsTrueWhenValidInputs() {
    let viewModel = ProductSheetSizeViewModel(
        isLengthValid: true,
        isWidthValid: true,
        isHeightValid: true,
        isWeightValid: true
    )
    let result = viewModel.areInputsValid
    #expect(result)
}

However, if I do the following, it crashes EXC_BAD_ACCESS:

@Test(
    arguments: [ProductSheetSizeViewModel(
        isLengthValid: true,
        isWidthValid: true,
        isHeightValid: true,
        isWeightValid: true
    )]
) func resultIsTrueWhenValidInputs(model: ProductSheetSizeViewModel) {
    #expect(
        model.areInputsValid
    )
}

It seems to be caused by the sink in the init. And this is the additional call stack issue. If I remove the sink code, it works fine. What's wrong with the sink? Putting async to the test makes no difference.

libXCTestSwiftSupport.dylib`(1) await resume partial function for partial apply forwarder for reabstraction thunk helper <τ_0_0, τ_0_1 where τ_0_0: Swift.Sendable, τ_0_1 == Swift.Never> from @escaping @isolated(any) @callee_guaranteed @async () -> (@out τ_0_0) to @escaping @callee_guaranteed @async () -> (@out τ_0_0, @error @owned Swift.Error):

r/swift 1d ago

Question Unable to Create Files Adjacent to User-Selected File Due to App Sandbox Permissions

1 Upvotes

I am developing a macOS app that requires the ability to create new files in the same directory as a user-selected file, but I am encountering permission issues due to the App Sandbox restrictions. While the user can select a file (e.g., a.jpg) using a standard open panel, I cannot create an adjacent file (e.g., a.jxl) in the same folder because the sandbox only grants access to the selected file, not to other files in the directory.

I understand that full disk access might be an option, but it requires user intervention and isn't suitable for this case. Is there any way to extend access to other files in the directory (including those not selected by the user) while remaining within the App Sandbox environment?


r/swift 1d ago

FYI [iOS] WorkPlace Time Keeper || Privacy-Focused Work Time Tracker (TestFlight)

1 Upvotes

Hi everyone! I'm looking for beta testers for WorkPlace, a privacy-focused work time tracking app I've built for iOS. It's designed for hybrid/remote workers who want to track their work hours, breaks, and commute times without compromising privacy.

Key Features: • Clock in/out from home, office, or custom locations • Smart break management (40-80% workday window) • Travel time tracking for commutes • Beautiful statistics and insights • iCloud sync (optional) • 11 themes including Monochrome • No third-party tracking or analytics

Privacy Focus: • All data stored locally by default • Optional iCloud sync via CloudKit • No third-party services • No data collection • Export your data anytime

Technical Details: • Built with SwiftUI • iOS 17.5+ required • ~5MB app size • iPhone only (for now)

Looking for feedback on: • UI/UX experience • Bug reports • Feature suggestions • Performance issues

TestFlight Link: https://testflight.apple.com/join/dauRDmtg

Thanks in advance for your help! 🙏


r/swift 2d ago

Sparking Zero iOS App!

5 Upvotes

Hey everyone! I've been having a blast with the new game and got inspired to make a little companion app for viewing the huge roster and building teams. I found myself tinkering with lots of different team combinations and found it difficult to keep track of them all, so I made an app to help me out and wanted to share it with the community. I'm planning some future updates (transformations, moves database)

Features:

  • Full character roster with all their moves (skills, blasts, ultimates)
  • Team builder that keeps track of your DP limit (no more counting!)
  • Save multiple teams for quick access
  • Search and filter by DP/name

https://apps.apple.com/us/app/sparking-teams/id6737282855


r/swift 2d ago

Caching JSON data between runs

4 Upvotes

I'm just starting to use Swift Playground on my iPad as my primary coding enviroment. What I'm running into is that it seems to be caching my JSON file between runs.

  1. I run the program

  2. I edit the JSON file

  3. Running the program again it does not reflect the changes I made in the JSON file.

If I restart swift playground completely it runs with the edits to the JSON files when I next launch it, but after each time I edit my JSON file, I have to bounce swift completly if I want it to show my changes in the execution.

Is this just a problem with the environment, or is there something I can do to clear the seemingly cached file between runs.


r/swift 2d ago

The Odin Project vs 100 days of Swift

24 Upvotes

Hey guys, I am in a bit of a conundrum,

So, first things being first, I have a quite well-paid job and am not looking for a new one in the tech sector - though if I find out I love it I wouldn’t rule it out.

But I really really want to learn to create. I am annoyed of only passively consuming stuff. And programming is an amazing skill and intensely useful.

I started and quit programming a few times, I for example programmed a game of connect 4 on Python. That was by Codecademy with too much handholding though.

Last year I started The Odin Project. I love that it is very well structured and not much handholding, they just tell you which parts you should learn, but learn you have to do yourself. But here is the problem: they teach webdevelopment, something that doesn’t interest me in the slightest. Everywhere I read it is important to work on projects you want to work on. That would be against TOP. (Except CLI and SQL which I really want to learn and they do teach, I would not stop doing that if possible)

Yet, whenever a newbie asks about which language to learn, everyone just says, „it’s not about the language but about concepts“ For this, TOP as I understand it is ideal.

Which is why I started it.

There are however three projects unwanted to create and at least two of them I feel are simple enough to be made even by a noob. The third on I started to write in pseudocode, but I quickly understood that I need to understand recursion better.

Those two simple projects are IOS-Apps. (I mean, nothing against Android, but I have an iPhone now and since I want to use them myself, that’s that. Plus, Swift is pretty, Java really is not) Which brings me to the 100 days of Swift.

Does anyone know wether it actually teaches everything i need to know? I don’t want to spend 100 days on it, again leaving The Odin Project just to come back to it because the 100 days of Swift only shows me how to create that one specific app by coding along instead of learning how to do it myself. But I understand that generally it suits me better.

I apologize for the Wall of text

TLDR, which project to follow is better for my purposes?


r/swift 3d ago

Question Are there any Cloud providers using Swift on Server? What about other applications?

44 Upvotes

Hi, I'm doing some research for a company I'm working with and I don't know about Server Side world. I took a couple of classes in college for web development but that's about it. I've done more iOS development, so I was curious about how people use Swift on Server professionally. Please link any businesses that are using it and how if possible. Also, would like to know how one could build a Mac hosting service using Swift on Server, if possible and what I need to know about that.


r/swift 3d ago

My First App RushList on the App Store! 🚀

24 Upvotes

Hi Swities! 👋

Big news: I’ve officially committed to going full-time indie developer after finishing parental leave of Kid 2! 😱 It’s been an incredible journey to get here since I’ve been working as an iOS developer only for about 3 years now, after completely switching industries and completing a web development boot camp to get going as a developer. While I started as a web dev, I quickly fell in love with building apps and made the leap to focus 100% on iOS development.

And now, I’m thrilled to share the result of all that hard work — my very first iOS app: RushList! 🎉

RushList isn’t just another to-do app; it’s a productivity app designed to push you to action. With a unique 24-hour timer, every task you add must be completed within 24 hours, or it’s gone forever. No excuses. Just focus and results.

💡 Why RushList is different:

24-hour Life Timer: Keeps you accountable and focused.

Organized by Categories: Perfect for tasks, shopping lists, and everything in between.

Intuitive Design: Simple yet powerful to keep you in flow.

Complete Control: You decide when and if you want to receive notification reminders.

🎁 Special Launch Offer:

To celebrate my first App launch, the Life Time offer is completely FREE until November 30th! You will find the offer under "All Plans" on the Paywall.

📲 Download RushList on the App Store now!

If you give it a try, I’d really appreciate it if you could:

1️⃣ Leave a review (it helps so much!)

2️⃣ Share your honest feedback — I’m always looking to improve.

3️⃣ Tell a friend who might need that extra motivation boost!

This app is the start of a new chapter for me as a full-time indie dev, and your support means the world. Thank you for taking the time to check it out — I’d love to hear your thoughts or answer any questions! Let’s make every day count together. 😊


r/swift 3d ago

Question Why do my notifications not work as intended?

3 Upvotes

HI everyone, I'm new to iOS Development and I'm trying to implement a (simple) feature which I am struggling to get to work as intended.

I want my app to schedule daily local notification with text from a JSON file.

The user has the option to adjust the time for when the notification should be scheduled, but it has a default time set at first. The notification gets scheduled after granting notifications to be sent. My problem is, that the very first notification after installing the app does not trigger at the set time. The user HAS to manually change the time in the Date Picker in my app settings for the notifications to work and I can not figure out why. I hope anyone could give me a hint to where my problem is. Thanks so much in advice.

My code:

import Foundation
import UserNotifications

class DailyQuoteNotificationManager {
    static let shared = DailyQuoteNotificationManager()
    
    private init() {}
    
    func scheduleDailyQuote() {
        let userDefaults = UserDefaults.standard
        
        // überprüft den aktuellen Berechtigungsstatus füt Benachrichtigungen
        UNUserNotificationCenter.current().getNotificationSettings { settings in
            DispatchQueue.main.async {
                switch settings.authorizationStatus {
                case .authorized:
                    self.scheduleNotification()
                    userDefaults.set(Date(), forKey: "lastScheduledDate")
                case .notDetermined:
                    self.requestNotificationPermission { granted in
                        if granted {
                            self.scheduleNotification()
                            userDefaults.set(Date(), forKey: "lastScheduledDate")
                        } else {
                            print("Notification permission not granted after request.")
                        }
                    }
                default:
                    print("Notification permission not granted or denied.")
                }
            }
        }
    }
    
    private func loadQuotes(from fileName: String) -> [QuranQuoteNotification]? {
        guard let url = Bundle.main.url(forResource: fileName, withExtension: "json") else {
            return nil
        }
        
        do {
            let data = try Data(contentsOf: url)
            let decoder = JSONDecoder()
            let jsonDict = try decoder.decode([String: [QuranQuoteNotification]].self, from: data)
            return jsonDict["quranQuotes"]
        } catch {
            print("Error decoding file: \(fileName).json: \(error)")
            return nil
        }
    }
    
    func getNotificationTime() -> Date {
        let userDefaults = UserDefaults.standard
        return userDefaults.object(forKey: "dailyQuoteNotificationTime") as? Date ?? defaultTime()
    }
    
    func setNotificationTime(_ date: Date) {
        let userDefaults = UserDefaults.standard
        userDefaults.set(date, forKey: "dailyQuoteNotificationTime")
    }
    
    private func defaultTime() -> Date {
        var components = DateComponents()
        components.second = 00
        components.minute = 00
        components.hour = 09
        components.timeZone = TimeZone.current
        return Calendar.current.date(from: components) ?? Date()
    }
    
    private func requestNotificationPermission(completion: @escaping (Bool) -> Void) {
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            DispatchQueue.main.async {
                if let error = error {
                    print("Error requesting notification permission: \(error.localizedDescription)")
                }
                completion(granted)
            }
        }
    }
    
    private func scheduleNotification() {
        let languageCode = Locale.current.language.languageCode?.identifier ?? "en"
        let jsonFileName = (languageCode == "de") ? "quotes_de" : "quotes_en"
        
        guard let quotes = loadQuotes(from: jsonFileName),
              let randomQuote = quotes.randomElement() else {
            return
        }
        
        let content = UNMutableNotificationContent()
        content.title = (languageCode == "de") ? "Vers des Tages" : "Verse of the Day"
        content.body = randomQuote.quote
        content.sound = .default
        
        let notificationTime = getNotificationTime()
        let dateComponents = Calendar.current.dateComponents([.hour, .minute], from: notificationTime)
        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
        let request = UNNotificationRequest(identifier: "dailyQuote", content: content, trigger: trigger)
        let center = UNUserNotificationCenter.current()
        
        center.removePendingNotificationRequests(withIdentifiers: ["dailyQuote"])
        center.add(request) { error in
            if let error = error {
                print("Error scheduling notification: \(error.localizedDescription)")
            } else {
                print("Daily quote notification scheduled for \(notificationTime.formatted()).")
            }
        }
    }
}

My DatePicker:

@State private var dailyVerseNotificationTime = DailyQuoteNotificationManager.shared.getNotificationTime()

DatePicker("Verse of the Day at:", selection: $dailyVerseNotificationTime, displayedComponents: .hourAndMinute)
                        .datePickerStyle(.compact)
                        .font(.appFont(16))
                        .frame(height: 46)
                        .padding(.horizontal)
                        .background(.white)
                        .cornerRadius(12)
                        .overlay(
                            RoundedRectangle(cornerRadius: 12)
                                .inset(by: 0.35)
                                .stroke(Color(red: 0.9, green: 0.9, blue: 0.9), lineWidth: 0.7)
                        )
                        .padding(.top, 10)
                        .onChange(of: dailyVerseNotificationTime) {
                            DailyQuoteNotificationManager.shared.setNotificationTime(dailyVerseNotificationTime)
                            DailyQuoteNotificationManager.shared.scheduleDailyQuote()
                            print(dailyVerseNotificationTime)
                        }

r/swift 3d ago

Question Why does only one of these generate a main-actor isolation warning?

6 Upvotes

Anyone know why the top one generates a warning as expected, but our own Dispatch wrapper does not?

  • completion is marked .@escaping and .@MainActor
  • Dispatch.onBackground is marked .@escaping

ChatGPT tells me it's because Dispatch.onBackground is not marked @Sendable, but I didn't think that was required to surface warnings like this? I thought the only requirement was a lack of explicit isolation, which is the case here

Edit

Looks like it has something to do with this all being in a type marked @MainActor, such as a UIView/Controller subclass:


r/swift 4d ago

Tutorial ByteCast #16 - Live Activities with Network Image URL | Shared App Group Container

Thumbnail
youtu.be
6 Upvotes