/r/swift
Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.
Dedicated to the Swift programming language released by Apple. More info in the Swift Wiki.
Please, check the FAQs before submitting.
General Swift Discussion
irc.freenode.net #swift-lang
Cocoa/Cocoa Touch Discussion
irc.freenode.net #cocoa-init
Keywords: swift, swiftlang, ios, os x, apps, apple, mac, iphone, ipad
/r/swift
And if so, how?
Hey,
I am new to Swift and MacOS development. Hope my question is not too silly. I am trying to use the #Preview feature in Xcode, but preview complains that I have `-O` instead of `-Onone` I'm trying to add `-Onone` from Cmake with `target_compile_options(${DEMO_TARGET} PUBLIC "-Onone")`, however it doesn't seem to take effect. `-Onone` is listed under Swift Compiler - Custom Flags, but Swift Compiiler - Code Generation still has Optimization Level `-O`
Note, I have tried `# set(CMAKE_SWIFT_FLAGS "-Onone")` but it didn't help either.
Here's my code:
main.swift
import SwiftUI
struct MyView: View {
var body: some View {
Text("Hello, World")
Text("Bye, World")
}
}
struct Demo: App {
var body: some Scene {
WindowGroup {
MyView() // Define a view hierarchy for the window.
}
}
}
Demo.main()
#Preview {
MyView()
}
and CMakeLists.txt
cmake_minimum_required(VERSION 3.30.4)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
project(NicegrafDemoWaterHouse
LANGUAGES CXX C Swift)
set(DEMO_TARGET DemoTarget)
add_executable(${DEMO_TARGET} MACOSX_BUNDLE source/main.swift)
target_compile_options(${DEMO_TARGET} PUBLIC "-Onone")
Hey guys,
Is it an ok practice to instantiate a @State viewmodel like this in a MainApp ?
struct MainApp: App {
@State var vm: MainAppViewModel = .init()
var body: some Scene {
if vm.hasAuthenticated {
MainView()
} else {
LoginView(vm: .init())
}
}
}
Every other view model is given to the views in the initializer for the the MainApp that is not possible it seems.
Ok so I’m obviously very new to all of this, so please bear with me…
When I start a new macOS app, I get a ContentView struct included. I’ve learned to make that follow NSViewRepresentable protocol and create a Coordinator so that I can use a Renderer to do Metal things.
Now, on day 23 of “Thirty Days of Metal” I’m finally running into a problem as I didn’t follow that author’s exact structure when building the code (as I was trying to stay in SwiftUI). Namely I don’t have a NSViewController (which I guess is part of AppKit?). The author processes all user input for a FlyCameraController through this class.
So it appears that either I need to figure out the SwiftUI way of getting keyboard and mouse input, or I need to figure out how to bring this NSViewController into my app.
Any suggestions? Thanks!!!
Hello everyone,
I’m starting a career change and aiming to move into app development with Swift. I have a few questions:
First, is this career in demand and does it have a promising future?
It seems essential to know other languages that complement Swift. In your opinion, which ones are important to master as well?
I noticed there are two main frameworks. I’m currently learning on Apple’s website with SwiftUI, but would you say mastering UIKit is also essential?
When I close and open App everything is saved perfectly. But when I run the app again just the TrainingsSessions are stored persistently and not the StrechingSesssions.
Why is that and what can I do - I have tried everything.
Maybe also for more context: first I only had one model (TrainingsSession) and then I added StrechingSession.
Here is my Code:
//
// ProjectM42App.swift
// ProjectM42
//
// Created by Dennis Sima on 03.09.24.
//
import SwiftUI
import SwiftData
import WidgetKit
@main
struct ProjectM42App: App {
@Environment(\.scenePhase) private var scenePhase
var sharedModelContainer: ModelContainer = {
let schema = Schema([
StrechingSession.self,
TrainingSession.self
])
let modelConfiguration = ModelConfiguration(schema: schema)
do {
return try ModelContainer(for: schema, configurations: [modelConfiguration])
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
var body: some Scene {
WindowGroup {
TabbarView()
}
.environmentObject(OnboardingManager())
.modelContainer(sharedModelContainer)
}
}
Hey guys,
Apple uses in its videos the MainActor annotation for classes inheritting the ObservableObject. Something like the below code.
But doesn't the MainActor annotation on a whole view model cause performance issues ? Or is it that the benefits outweigh the disadvantages ?
What framework would you use to create an app like pixelmator?
Does anyone here have this course with them? I would really appreciate it. Thank you
I’m having an issue with the location manager: on the first run of the app on a physical device, the current location defaults to Berlin—even though I’m not in Berlin. After I close and reopen the app on my phone, it shows my correct location, however now i obviously can't debug anymore.
I thought this Berlin location might be somehow stored in cache, so I wrote a new most basic LocationManager class that is just supposed to print out the current location to make the problem as transparent as possible.
However even this basic class returns Berlin on the first run of the app and my real location only after the app restart.
This is the print that I always get:
I even edited the simulated location in my test plan from None to Honolulu, to see if this would have any effect on the displayed location, but no luck. It's always Berlin.
Can anybody tell, what I'm missing here? It sounds like an extreme easy to solve problem, but I just don't see any reason behind it.
Here's the code for the simplified LocationManger class:
import Foundation
import CoreLocation
final class LocationManager: NSObject, CLLocationManagerDelegate, ObservableObject {
@Published var location: CLLocationCoordinate2D?
var manager = CLLocationManager()
override init() {
self.manager.requestWhenInUseAuthorization()
super.init()
self.manager.delegate = self
checkLocationAuthorization()
}
func checkLocationAuthorization() {
switch manager.authorizationStatus {
case .notDetermined:
manager.requestWhenInUseAuthorization()
case .restricted:
print("Location restricted")
case .denied:
print("Location denied")
case .authorizedAlways:
print("Location authorizedAlways")
case .authorizedWhenInUse:
print("Location authorized when in use")
manager.requestLocation()
@unknown default:
print("Location service disabled")
}
}
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
checkLocationAuthorization()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
location = locations.first?.coordinate
print("[INFO]: Latidtude: \(String(describing: location!.latitude)), Longitude: \(String(describing: location!.longitude))")
}
func locationManagerDidResumeLocationUpdates(_ manager: CLLocationManager) {
print("Location updates resumed.")
}
func locationManagerDidPauseLocationUpdates(_ manager: CLLocationManager) {
print("Location updates paused.")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: any Error) {
print("ERROR: \(error)")
}
}
EDIT: I debugged it be rewriting the bug in Go. See below.
I have some complicated algorithmic code that I'm trying to get to work. And well, obviously I've introduced an out of range array access bug. The problem is, the stack trace does not identify where in the code I have attempted to access the array where it was out of bounds. Having previously done a lot of programming in Go and Rust I cannot for the life of me believe that the error messages in Swift can be so useless.
Here is the stack trace that gets printed. It points to the place in the standard library where array access is done, which is of course of zero value to the developer. Is the answer really that if you have an out of range array access bug, you must check every single array access done in your entire program and potentially every library you import too?
Swift/ContiguousArrayBuffer.swift:675: Fatal error: Index out of range
Stack dump:
0.Program arguments: /Library/Developer/CommandLineTools/usr/bin/swift-frontend -frontend -interpret product-except-self.swift -Xllvm -aarch64-use-tbi -enable-objc-interop -stack-check -sdk /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -color-diagnostics -new-driver-path /Library/Developer/CommandLineTools/usr/bin/swift-driver -empty-abi-descriptor -resource-dir /Library/Developer/CommandLineTools/usr/lib/swift -module-name main -disable-clang-spi -target-sdk-version 15.0 -target-sdk-name macosx15.0 -external-plugin-path /Library/Developer/Developer/usr/lib/swift/host/plugins#/Library/Developer/Developer/usr/bin/swift-plugin-server -external-plugin-path /Library/Developer/Developer/usr/local/lib/swift/host/plugins#/Library/Developer/Developer/usr/bin/swift-plugin-server -plugin-path /Library/Developer/CommandLineTools/usr/lib/swift/host/plugins -plugin-path /Library/Developer/CommandLineTools/usr/local/lib/swift/host/plugins
1.Apple Swift version 6.0 (swiftlang-6.0.0.9.10 clang-1600.0.26.2)
2.Compiling with effective version 5.10
3.While running user code "product-except-self.swift"
Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it):
0 swift-frontend 0x00000001066030fc llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) + 56
1 swift-frontend 0x0000000106601350 llvm::sys::RunSignalHandlers() + 112
2 swift-frontend 0x00000001066036c8 SignalHandler(int) + 292
3 libsystem_platform.dylib 0x0000000192e74184 _sigtramp + 56
4 libswiftCore.dylib 0x00000001a3a7ed10 $ss17_assertionFailure__4file4line5flagss5NeverOs12StaticStringV_A2HSus6UInt32VtFySRys5UInt8VGXEfU_yAMXEfU_yAMXEfU_ + 240
5 libswiftCore.dylib 0x00000001a3a7ebd8 $ss17_assertionFailure__4file4line5flagss5NeverOs12StaticStringV_A2HSus6UInt32VtFySRys5UInt8VGXEfU_yAMXEfU_ + 344
6 libswiftCore.dylib 0x00000001a3a7e534 $ss17_assertionFailure__4file4line5flagss5NeverOs12StaticStringV_A2HSus6UInt32VtF + 188
7 libswiftCore.dylib 0x00000001a3a5d988 $ss16_DependenceTokenVABycfC + 0
8 libswiftCore.dylib 0x00000001a3a5e240 $sSayxSicig + 88
9 libswiftCore.dylib 0x000000010a0d4420 $sSayxSicig + 18446744071132635704
10 libswiftCore.dylib 0x000000010a0d4070 $sSayxSicig + 18446744071132634760
11 swift-frontend 0x00000001010fcc20 llvm::orc::runAsMain(int (*)(int, char**), llvm::ArrayRef<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::optional<llvm::StringRef>) + 1940
12 swift-frontend 0x00000001010105f4 swift::SwiftJIT::runMain(llvm::ArrayRef<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>) + 172
13 swift-frontend 0x000000010101e000 swift::RunImmediately(swift::CompilerInstance&, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, swift::IRGenOptions const&, swift::SILOptions const&, std::__1::unique_ptr<swift::SILModule, std::__1::default_delete<swift::SILModule>>&&) + 1028
14 swift-frontend 0x0000000100fb259c processCommandLineAndRunImmediately(swift::CompilerInstance&, std::__1::unique_ptr<swift::SILModule, std::__1::default_delete<swift::SILModule>>&&, llvm::PointerUnion<swift::ModuleDecl*, swift::SourceFile*>, swift::FrontendObserver*, int&) + 536
15 swift-frontend 0x0000000100fae004 performCompileStepsPostSILGen(swift::CompilerInstance&, std::__1::unique_ptr<swift::SILModule, std::__1::default_delete<swift::SILModule>>, llvm::PointerUnion<swift::ModuleDecl*, swift::SourceFile*>, swift::PrimarySpecificPaths const&, int&, swift::FrontendObserver*) + 2044
16 swift-frontend 0x0000000100fad6e4 swift::performCompileStepsPostSema(swift::CompilerInstance&, int&, swift::FrontendObserver*) + 2888
17 swift-frontend 0x0000000100fb0714 performCompile(swift::CompilerInstance&, int&, swift::FrontendObserver*) + 2940
18 swift-frontend 0x0000000100faef58 swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) + 3572
19 swift-frontend 0x0000000100f3601c swift::mainEntry(int, char const**) + 3680
20 dyld 0x0000000192abc274 start + 2840
So, unable to glean where in the code the problem was with Swift, out of interest I rewrote the code in Go with the exact same bug. Just out of interest. Here is the output from the Go trace
panic: runtime error: index out of range [-1]
goroutine 1 [running]:
main.f({0x140001a6020, 0x4, 0x4})
/Users/dka/swift/exercises/main.go:29 +0x118
main.main()
/Users/dka/swift/exercises/main.go:6 +0x4c
exit status 2
Tells me the exact line and column in the code where the array access went wrong (there are three array accesses on that line, so the column sure helps). This experience with Swift was so negative that I'm looking into GUI libraries in other languages and reconsidering if I want to dabble in native app development for macOS.
Hi everyone!
Last summer, I had a big project at work: I needed to describe all our project’s CLI commands using “make” (testing, linting, and tons of automation we’ve built up over more than 10 years). We didn’t just want “make” as a simple proxy; we wanted to add some extra functionality—like auto-installing dependencies and setting everything up in a project directory for better control. It ended up being a pretty powerful make setup!
I really liked what we achieved, but along the way, I realized that some things in make aren’t exactly straightforward or user-friendly. But the biggest issue was that most Swift developers focus on UI apps and aren’t super familiar with shell scripting or make, so commands become hard to understand and maintain—definitely not ideal for complex setups.
Anyway, after all that, I started dreaming about a similar tool but written in Swift. I wanted a way to define all commands in Swift and decided to build it myself! (First I did some research, but nothing out there quite met my needs.)
So, let me introduce “Sake” (because it’s “S(wift) make”—and who doesn’t like the Japanese drink? 😄). I’ve built out the core features I think a tool like this should have, and it’s ready for non-production projects!
Here’s a quick example of what it looks like
You can check out the repo here: Sake on GitHub. The project actually uses Sake itself to automate routine tasks!
I invite you to try it out and would love to hear your feedback!
The things I love the most about Swift are all a part of Rust as well so if you can grasp these concepts you'll feel right at home: Optionals, Generics, Associated Types, Enums, Structs (values), and Classes (references). I think those are the main features I see in common. I'd encourage looking into Rust and seeing if its strengths would be beneficial to you. With tools like WebAssembly you can even mix the 2 languages up.
How do I replicate this with .navigationDestination since isActive is depreciated? All I need is to redirect like this
NavigationLink(destination: DetailsView(), isActive: $shouldNavigate) { EmptyView() }
Vapor developers! 🚀 Do we need an Laravel Artisan-like CLI tool for code generation in our Vapor projects? Anyone using something similar already? Would love to hear your experiences and thoughts on scaffolding models, controllers, etc.
Hey everyone! Actually I am planning to buy a macbook for iOS development. I am in a position where I can either afford a brand new M3 air 15" (24gb 512gb with apple care) or a used M1 Pro (16gb 512gb). I will be using this machine for at least 4 years and maybe more but not less than that. I will be using it for native ios development, content consumption (a lot), open source contributions and as every developer (a lot of chrome tabs) and at least 2 ios simulators and even android studio for my kotlin projects. What would be better? Please don't recommend Mac Mini that is not in the list at all due to a lot of travelling between cities. Hoping for a detailed answers 😊. And if someone is suggesting for a M1 pro then why? Isn't it that a newer M3 chip is better than that? Note : I know I have been just asking for suggestions since a month but guys, I need to look for every single option to before investing such a big amount into a machine that will be used for years. I hope you guys understand 😊.
I created this SPM plugin that checks for usages of transitive dependencies and let you know at build time 🚀
https://github.com/Nikoloutsos/explicitDependencyImportCheck
This makes dependencies more clean in your project.
About a month ago I posted about starting this project and now I can finally present you the first release of Yatoro - Apple Music player that runs in your terminal emulator!
Written in Swift, btw.
Edit: The gif doesn't get loaded here for some reason, check it on GitHub
Some explanations on what happens in the preview:
:search the tool
):a -c a n
) (add from catalog search all songs after current song):set 4:20
):sce
)Check it out here.
The features are still quite limited, it still needs a lot of work, so contributions are very welcome!
There is always this thing that I struggle with and I still don't have a consensus on which approach to adopt:
Should a view represent the object/s exactly or should a view be able to represent anything without knowing about what it's representing?
Let's use an example.
My app primarily represents destinations i.e. [Destination]
. Each destination has a collections of animals [Animal]
and each animal has a number of properties.
Now I want to represent these animals in a view as a list/collectionView, etc.
When I create the view, I have a choice of passing in the destination
, the animals
or only the properties that the list needs to show such as an array of tuples e.g. [(animalID, animalName, animalImage, etc)].
If I pass in the destination upon instantiation of the view, one advantage is that if I make changes to the animals from outside of the view such as deleting or adding animals, etc - the list/collectionView can easily reflect this. All logic for exactly what the list will display is handled in the view itself, parsing out the animalName, animalImage, etc. I primarily use UIKIt, so I would likely use Combine and listen for changes on the destination
and do all updates inside the collectionView
.
Another advantage is that if I decide later that I need some extra information from destination
such as climate
or habitat
, it will already be available in the view for me to use.
If I pass the animals
upon instantiation, I could easily add/remove animals on the view with methods on the view such as add(_ animals)
or remove(_ animals)
or update(_ animals)
I can also easily use other properties of any animal for display, such as animalSize
, etc.
The disadvantage of passing in a destination
or animals
is that the view becomes less testable with strong coupling because I can't pass in anything other that Destination
or [Animal]
.
The final option and one advocated by a number of very experienced developers is to only pass in only the exact properties that this view needs in order to function (see the tuple array pseudo-code from above). The advatage here is that the view/collectionView really doesn't give a damn about what it is displaying. You are passing in simple types i.e String, Data, Int, etc, so it is really easy to test and the view doesn't have to do much if any logic processing on the data. It just needs to present it.
I really don't know and can't decide what to do.
I have used all three approaches in the past and the one that actually feels most natural is passing in the destination
or just a reference to the viewModel
which knows about evertying in my app. That way I can access whatever information I want if I decide to change my view later such as adding some other stuff, etc. Sorry - didn't mean to spring the viewModel
option on you right at the end here but it is a viable option.
But because I gravitate towards this approach, I have had difficulty in getting into testing in general. The whole task of testing is just extremely daunting to me.
So, what do you think is the best approach?
Which approaches do you use and why do you think that those are the best approaches?
Are there other advantages/disadvantages that I'm not aware of?
I would love to get some genuine feedback to help me put this mental debate to rest once and for all.
Thanks.
I found the 30 days of Metal tutorial online and decided to try to follow it. First example is just getting the default Metal device. I tried to run this in a playground as described in the tutorial and got an ‘LLDB RPC Server has crashed’ message. So frustrating…. It works fine in a command-line macOS program, and it also works in the Playground App.
Anyone else run into this issue?
I am newish to developing apps, I want to explore with my own set for ML. I want to know if:
A: It is doable to train my model and learn from my pictures?
B: Try to match pictures people would upload of their products to my pictures.
Any idea where I could look / learn about all of this?
Thank you so much ^^
Hey folks,
I recently graduated in July of this year, and I’m currently not employed. I’m really interested in participating in the Swift Student Challenge next year, but I’m not entirely sure if I meet the eligibility criteria since I'm technically no longer a student.
Has anyone been in a similar situation or know if recent grads like me are still eligible? And if I'm not eligible, does anyone have advice on what steps I could take to qualify again, like enrolling in an accredited course or program that Apple would recognize?
Thanks for any insights you can provide!
In the code below I have a test view that shows a list of flashcards (CardView structures). You can swipe the cards left or right, after which the closure provided during initialization of CardView is called. When you swipe a card left, the closure is run with its parameter isCorrect set to false.
The closure that I provide to the CardView runs removeCard(card: Card, isCorrect: Bool) method from the parent's view inside a withAnimation block.
removeCard removes provided card from a @State array of cards. If isCorrect parameter is set to true, then that's it. However, if isCorrect parameter is set to false, it then inserts the removed card at the beginning of the cards array.
Here's a problem: if CardView runs the closure with isCorrect parameter set to true, everything is correct, SwiftUI animates removal of the CardView nicely. However, if isCorrect parameter is set to false (i.e. Card is removed from the array and is inserted at the begining) SwiftUI doesn't render corresponding CardView. It creates it, and even shows its frame (red border), but the CardView itself is not visible.
What even stranger, if I call removeCard with isCorrect set to false from a button in the parent view ("Shuffle Cards" button) SwiftUI animates the removal and insertion nicely, all CardViews are rendered.
One workaround that I found is that if the closure that I provide to the CardView calls removeCard without withAnimation block and if I remove a card from the array inside DispatchQueue.main.async, SwitUI would render CardView correctly. However, now there is no animation. And I don't understand why this solution works.
struct TestView: View {
@State private var cards: [Card] = [
Card(prompt: "test", answer: "test"),
Card(prompt: "test2", answer: "test2"),
Card(prompt: "test3", answer: "test3")
]
var body: some View {
VStack {
VStack {
ForEach(cards) { card in
ZStack {
CardView(card: card) { isCorrect in
withAnimation {
removeCard(card: card, isCorrect: isCorrect)
}
}
.border(.red)
}
}
}
Spacer()
Button("Shuffle Cards") {
withAnimation {
guard let lastCard = cards.last else { return }
removeCard(card: lastCard, isCorrect: false)
}
}
}
}
func removeCard(card: Card, isCorrect: Bool) {
guard let index = getCardIndex(card) else { return }
print(card)
print("index: ", index)
cards.remove(at: index)
if !isCorrect {
cards.insert(card, at: 0)
}
}
func getCardIndex(_ card: Card) -> Int? {
return cards.lastIndex(where: { $0.id == card.id })
}
}
Workaround: struct TestView: View { @State private var cards: [Card] = [ Card(prompt: "test", answer: "test"), Card(prompt: "test2", answer: "test2"), Card(prompt: "test3", answer: "test3") ]
var body: some View {
VStack {
VStack {
ForEach(cards) { card in
ZStack {
CardView(card: card) { isCorrect in
removeCard(card: card, isCorrect: isCorrect)
}
.border(.red)
}
}
}
Spacer()
Button("Shuffle Cards") {
withAnimation {
guard let lastCard = cards.last else { return }
removeCard(card: lastCard, isCorrect: false)
}
}
}
}
func removeCard(card: Card, isCorrect: Bool) {
guard let index = getCardIndex(card) else { return }
cards.remove(at: index)
DispatchQueue.main.async {
if !isCorrect {
cards.insert(card, at: 0)
}
}
}
func getCardIndex(_ card: Card) -> Int? {
return cards.lastIndex(where: { $0.id == card.id })
}
}
I’n having hard time using storyboard in UIKIt. can you please give some tips
EDIT: Thank you all for your response. It is indeed very helpful. This sub is actually cool that people here are willing to pass down knowledge and help.
Hello,
I was trying to solve the error "Command CodeSign failed with a nonzero exit code" that occurs when I try to archive and publish my app. A suggested solution is to fix the Bundle ID. Now I think they match on Xcode and the Developer Portal. But the CodeSign error still persists. I realized the Team IDs on the Portal and my Mac local keychain do not match.
Sorry if these questions are obvious or stupid. Thanks so much for any advice.
Hi everyone, I've made a simple app for chatting with llama 3.2 locally. The TestFlight is here: https://testflight.apple.com/join/1k5Z276J and the code is here: https://github.com/syousif94/senti
I would love some feedback and testers!
I’ve been using ChatGPT with some success but it makes a lot of mistakes and is limited to about 300 lines of code before getting wonky.