Swift is a powerful and intuitive programming language for Apple platforms and beyond.

Posts under Swift tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

How can you communicate that a .xcframework is a dependency OF the swift package inside Swift package definition?
I am sort of trying to do the opposite of what others are doing. I have a target called CopyFramework that creates a CopyFramework.framework within my main xcproj file. I set up this target because a specific framework (we can call it Tools.xcframework) is distributed as a binary. That framework file lives within the code. Tools.xcframework is structured like so Tools.xcframework (Coding/testBuild/DynamicToolFrameworks/Tools.xcframework) info.plist ios-arm64/ Tools.xcframework/ Tools (executable file) Tools.bundle Headers/ Info.plist Modules/ Tools.swiftmodule/ arm64-apple-ios.abi.json arm64-apple-ios.private.swiftinterface arm64-apple-ios.swiftdoc arm64-apple-ios.swiftinterface module.modulemap module.private.modulemap PrivateHeaders/ ios-arm64_x86_64-simulator/ When the CopyFramework target is run xcode does a few steps which copy the correct version of this framework to derived data. Process Tools.xcframework (iOS) Coding/testBuild/DynamicToolFrameworks/Tools.xcframework /Library/Developer/Xcode/DerivedData/testBuild-sha/Build/Products/Debug-iphoneos/Tools.framework ios cd /Users/calebkierum/Coding/testBuild builtin-process-xcframework --xcframework Coding/testBuild/DynamicToolFrameworks/Tools.xcframework --platform ios --target-path Library/Developer/Xcode/DerivedData/testBuild-sha/Build/Products/Debug-iphoneos Meaning essentially that the Tools.xcframework for the proper platform is taken from Tools.xcframework/ios-arm64 and copied to Library/Developer/Xcode/DerivedData/testBuild-sha/Build/Products/Debug-iphoneos/Tools.xcframework I am writing a Swift Package that needs to be able to reference the correct Tools.xcframework. I have set it up like so: let package = Package( name: "CoreObjC", platforms: [.iOS(.v17), .macCatalyst(.v17)], products: [ .library(name: "CoreObjC", targets: ["CoreObjC"]), ], dependencies: [ // Does something to here ??? //.package(path: "../testBuild") ], targets: [ .target( name: "CoreObjC", dependencies: [ // Here I would like to be referencing the CopyFramework.framework target within my buildTest.xcproj file .product(name: "CopyFramework", package: /*??? its not in a swift package its a part of an xcproj file*/) ], path: "CoreObjC", publicHeadersPath: "Headers", linkerSettings: [ .linkedFramework("Tools", .when(platforms: [.iOS])), .linkedLibrary("c++") ] ), ], cxxLanguageStandard: CXXLanguageStandard.gnucxx14 ) Now obviously this does not work. I do not know how to communicate to the Package.swift file that the binary dependency is a framework target within my xcproj file. If I do run the target CopyFramework followed by building CoreObjC it works though (so long as you comment out the bits trying to reference CopyFramework). Running the CopyFramework target processes the Tools.xcframework and copies the proper xcframework sub folder to Derived data and the Swift Package build system seems to be able to see it. Is there a way I can get rid of this manual step? Make it so that when I build the CoreObjC target (swift package) that either CopyFramework is run or some other process is run to get the proper xcframework out of Coding/testBuild/DynamicToolFrameworks/Tools.xcframework and into DerivedData? Is it even theoretically possible to have a Swift Package reference a target in a normal xcproj file?
0
0
13
9h
Module not found when using inheritance
PLATFORM AND VERSION Development environment: Xcode 16.4 (16F6), macOS 15.5 (24F74) Run-time configuration: iOS 18.3.1 DESCRIPTION OF PROBLEM I cannot build my app due to a module not found error when I'm importing Sample-Swift.h header to an ObjectiveC file. I need to use Swift code to ObjectiveC file with Swift code using an external XCFramework. It seems to be related to a mix with ObjectiveC and Swift code when Swift code uses class inheritance from FZWorkoutKit class. With a full Swift project, no issue. STEPS TO REPRODUCE Project https://fizzup.s3.amazonaws.com/files/public/Sample-WK.zip Open the provided project and try to build it. The issue occurs. In MyObject.m file, if you comment the first import (Sample-Swift.h), no issue occurs but I cannot use my Swift code (MyFile class). Uncomment the line commented in step 1. Go to MyFile.swift and change class inheritance from GoModeController (from FZWorkoutKit framework) to UIView (from UIKit). No issue occurs.
0
0
27
1d
Error querying optional Codable with SwiftData
I'm building a SwiftUI app using SwiftData. In my app I have a Customer model with an optional codable structure Contact. Below is a simplified version of my model: @Model class Customer { var name: String = "" var contact: Contact? init(name: String, contact: Contact? = nil) { self.name = name self.contact = contact } struct Contact: Codable, Equatable { var phone: String var email: String var allowSMS: Bool } } I'm trying to query all the Customers that have a contact with @Query. For example: @Query(filter: #Predicate<Customer> { customer in customer.contact != nil }) var customers: [Customer] However no matter how I set the predicate I always get an error: BugDemo crashed due to an uncaught exception NSInvalidArgumentException. Reason: keypath contact not found in entity Customer. How can I fix this so that I'm able to filter by contact not nil in my Model?
0
0
43
2d
Is there anywhere to get precompiled WhisperKit models for Swift?
If try to dynamically load WhipserKit's models, as in below, the download never occurs. No error or anything. And at the same time I can still get to the huggingface.co hosting site without any headaches, so it's not a blocking issue. let config = WhisperKitConfig( model: "openai_whisper-large-v3", modelRepo: "argmaxinc/whisperkit-coreml" ) So I have to default to the tiny model as seen below. I have tried so many ways, using ChatGPT and others, to build the models on my Mac, but too many failures, because I have never dealt with builds like that before. Are there any hosting sites that have the models (small, medium, large) already built where I can download them and just bundle them into my project? Wasted quite a large amount of time trying to get this done. import Foundation import WhisperKit @MainActor class WhisperLoader: ObservableObject { var pipe: WhisperKit? init() { Task { await self.initializeWhisper() } } private func initializeWhisper() async { do { Logging.shared.logLevel = .debug Logging.shared.loggingCallback = { message in print("[WhisperKit] \(message)") } let pipe = try await WhisperKit() // defaults to "tiny" self.pipe = pipe print("initialized. Model state: \(pipe.modelState)") guard let audioURL = Bundle.main.url(forResource: "44pf", withExtension: "wav") else { fatalError("not in bundle") } let result = try await pipe.transcribe(audioPath: audioURL.path) print("result: \(result)") } catch { print("Error: \(error)") } } }
0
0
39
3d
Detect when app window is being moved
Is there a way to detect when your apps (or any app I guess) is being moved by the user clicking and dragging the main window around the desktop at all? I'm trying to find out if there's a way I can find out if a window is being clicked and dragged and whether there's certain triggers to the movement a little bit like shaking an iPhone with Shake to Undo. Thanks
0
0
19
3d
NavigationStack wrong behaviour in iOS 18.3
Hi, Anybody knows will this occurs when using navigationStack at iOS 18.3? The navigationStack not stay at safeareas the code as simple as that: NavigationStack(path: $navManager.path) { VStack { Text("Hello") } .navigationDestination(for: Route.self) { route in switch route { .... } } } .environmentObject(navManager) .environment(logic)
0
0
60
3d
Unable to send/receive IPv6 Mutlicast packets on NWConnectionGroup using Apple NF
Hello Everyone, I am currently using macOS 15.5 and XCode 16.4. I am using the following code to send/receive multicast packets on multicast group ff02::1 and port 49153 using Apple NF's NWConnectionGroup. import Network import Foundation // Creating a mutlicast group endpoint let multicastIPv6GroupEndpoint: NWEndpoint = NWEndpoint.hostPort(host: NWEndpoint.Host.ipv6(IPv6Address("ff02::1")!), port: NWEndpoint.Port("49153")!) do { let multicastGroupDescriptor: NWMulticastGroup = try NWMulticastGroup (for: [multicastIPv6GroupEndpoint]) let multicastConnectionGroupDescriptor = NWConnectionGroup (with: multicastGroupDescriptor, using: .udp) multicastConnectionGroupDescriptor.stateUpdateHandler = { state in print ("🕰️ Connection Group state: \(state)") if state == .ready { multicastConnectionGroupDescriptor.send (content: "👋🏻 Hello from the Mac 💻".data (using: .utf8)) { err in print ("➡️ Now, I am trying to send some messages.") if let err = err { print ("💥 Error sending multicast message: \(err)") } else { print ("🌚 Initial multicast message sent") } } } } multicastConnectionGroupDescriptor.setReceiveHandler { message, content, isComplete in if let content = content, let messageString = String (data: content, encoding: .utf8) { print ("⬅️ Received message: \(messageString)") } } multicastConnectionGroupDescriptor.start (queue: .global()) } catch { print ("💥 Error while creating Multicast Group: \(error)") } RunLoop.main.run() I am able to successfully create a NWConnectionGroup without any warnings/errors. The issue occurs when the stateUpdateHandler's callback gets invoked. It first gives me this warning: nw_listener_socket_inbox_create_socket IPV6_LEAVE_GROUP ff02::1.49153 failed [49: Can't assign requested address But then it shows me that the state is ready: 🕰️ Connection Group state: ready After this, when the send is performed, it gives me a bunch of errros: nw_endpoint_flow_failed_with_error [C1 ff02::1.49153 waiting parent-flow (unsatisfied (Local network prohibited), interface: en0[802.11], ipv4, ipv6, uses wifi)] already failing, returning nw_socket_connect [C1:1] connectx(7, [srcif=0, srcaddr=::.62838, dstaddr=ff02::1.49153], SAE_ASSOCID_ANY, 0, NULL, 0, NULL, SAE_CONNID_ANY) failed: [48: Address already in use] nw_socket_connect [C1:1] connectx failed (fd 7) [48: Address already in use] nw_socket_connect connectx failed [48: Address already in use] nw_endpoint_flow_failed_with_error [C1 ff02::1.49153 in_progress socket-flow (satisfied (Path is satisfied), interface: en0[802.11], ipv4, ipv6, dns, uses wifi)] already failing, returning There is no other background process running on the same port. I tried using different ports as well as multicast groups but the same error persists. The same code works fine for an IPv4 multicast group. I have following questions: Why am I getting these errors specifically for IPv6 multicast group but not for IPv4 multicast group? Are there any configurations that needed to be done in order to get this working?
5
0
57
19h
SwiftMacros Not able to access of main project XCTest File.
I have developed a Swift macro called @CodableInit in the SwiftCodableMacro module, and I’m able to use it successfully in my main project. Here’s an example usage: import SwiftCodableMacro @CodableInit // This is for Codable macros public class ErrorMonitoringWebPlugin { public var identifier: UUID = UUID() // MARK: - Codable required public init(from decoder:Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) identifier = try values.decode(UUID.self, forKey: .identifier) } } However, when I try to write a unit test for the ErrorMonitoringWebPlugin class, I encounter an issue. Here's the test case: func testCodableSubjectIdentifierShouldEqualDecodedSubjectIdentifier() { self.measure { let encoder = JSONEncoder() let data = try? encoder.encode(subject) //Here I am getting this error Class 'JSONEncoder' requires that 'ErrorMonitoringWebPlugin' conform to 'Encodable' let decoder = JSONDecoder() let decodedSubject = try? decoder.decode(ErrorMonitoringWebPlugin.self, from: data!) XCTAssertEqual(subject.identifier, decodedSubject?.identifier) } } The compiler throws an error saying: Class 'JSONEncoder' requires that 'ErrorMonitoringWebPlugin' conform to 'Encodable' Even though the @CodableInit macro is supposed to generate conformance, it seems that this macro-generated code is not visible or active inside the test target. How can I ensure that the @CodableInit macro (from SwiftCodableMacro) is correctly applied and recognized within the XCTest target of my main project?
0
0
21
2d
Contact UISearchBar missing.
Feedback id: FB16140301 Below are the steps to reproduce the bug in Contacts app. Open Contacts app. Now search for a contact and didSelect that contact. Now slightly hold swipe right(from view's center leading position) as to pop the view but not fully swipe, now release the finger and you can see the back nav bar button missing and tapping the back button position also doesn't perform dismiss action. Now do fully swipe from left to right to dismiss(pop) current view. Here you can see the search bar missing.-> That's the bug.
0
0
29
4d
Snapshot error
Hey everyone, I have a problem with an app im creating. The code doesn't have any errors but the console has this that pops up: Snapshot request 0x1054191d0 complete with error: <NSError: 0x10541a970; domain: FBSSceneSnapshotErrorDomain; code: 4; "an unrelated condition or state was not satisfied"> { NSLocalizedDescription = an error occurred during a scene snapshotting operation; }
1
0
34
3d
How to detect if an iPad is configured as a Shared iPad (Apple School Manager)?
I'm working on an iOS/iPadOS app and need to determine programmatically whether the device is a Shared iPad as configured through Apple School Manager (ASM). Shared iPads allow multiple users to sign in with Managed Apple IDs and are typically used in educational environments. I want to identify this configuration at runtime within my app. I’ve looked into UIDevice, NSProcessInfo, and MDM-related APIs but haven't found a reliable way to detect whether the current device is a Shared iPad. Is there an API or method to check if the current iPad is configured as a Shared iPad (via ASM)? Any guidance or code examples would be appreciated.
0
0
17
4d
@Observable with generic typed throw breaks SwiftCompile
@Observable seems not to work well with generic typed throw. The following code using @Observable with non-generic typed throw builds good: @Observable class ThrowsLoadingViewModel<R, E: Error> { private(set) var isLoading = true private(set) var error: E? = nil private(set) var data: R? = nil private var task: () throws(Error) -> R init(task: @escaping () throws(E) -> R) { self.task = task } func load() { do throws(Error) { self.data = try task() } catch { // self.error = error } self.isLoading = false } } But if I change Line 7 and 14 to generic, it'll breaks the build with a "Command SwiftCompile failed with a nonzero exit code" message : @Observable class ThrowsLoadingViewModel<R, E: Error> { private(set) var isLoading = true private(set) var error: E? = nil private(set) var data: R? = nil private var task: () throws(E) -> R init(task: @escaping () throws(E) -> R) { self.task = task } func load() { do throws(E) { self.data = try task() } catch { // self.error = error } self.isLoading = false } } A the same time, if I remove @Observable, the generic typed throw works again: class ThrowsLoadingViewModel<R, E: Error> { private(set) var isLoading = true private(set) var error: E? = nil private(set) var data: R? = nil private var task: () throws(E) -> R init(task: @escaping () throws(E) -> R) { self.task = task } func load() { do throws(E) { self.data = try task() } catch { // self.error = error } self.isLoading = false } } Currently the possible solution seems to fall back to use ObservableObject...
0
0
12
4d
SwiftData #Predicate in Swift 6 language mode
I'm trying to migrate over to the Swift 6 language mode, but the biggest issue I'm facing is that any use of SwiftData #Predicate or SortDescriptor results in this warning from the compiler: Type 'ReferenceWritableKeyPath<GuruSchemaV2.Rubric, Bool>' does not conform to the 'Sendable' protocol; this is an error in the Swift 6 language mode Here is an example predicate, from a static method on the Rubric type: static func notArchived() -> Predicate<Rubric> { return #Predicate<Rubric> { rubric in !rubric.archived } } And the error highlights line 5 of the expanded macro: Foundation.Predicate<Rubric>({ rubric in PredicateExpressions.build_Negation( PredicateExpressions.build_KeyPath( root: PredicateExpressions.build_Arg(rubric), keyPath: \.archived ) ) }) What is the correct way to reference properties of a model type using #Predicate?
0
1
33
5d
Horrendous Swift overlay of vDSP Fourier Transform functions
I'm very unpleased to have found out the hard way, that vDSP.FFT&amp;lt;T&amp;gt; where T : vDSP_FourierTransformable and its associated vDSP_FourierTransformFunctions, only does real-complex conversion!!! This is horribly misleading - the only hint that it calls vDSP_fft_zrop() (split-complex real-complex out-of-place) under the hood, not vDSP_fft_zop()[1], is "A 1D single- and double-precision fast Fourier transform." - instead of "a single- and double-precision complex fast Fourier transform". Holy ******* ****. Just look at how people miss-call this routine. Poor him, realizing he had to log2n+1 lest only the first half of the array was transformed, not understanding why [2]. And poor me, having taken days investigating why a simple Swift overlay vDSP.FFT.transform may execute at 1.4x the speed of vDSP_fft_zopt(out-of-place with temporary buffer)! [3] [1]: or better, vDSP_fft_zopt with the temp buffer alloc/dealloc taken care of, for us [2]: for real-complex conversion, say real signal of length 16. log2n is 4 no problem, but then the real and imaginary vectors are both length 8. Also, vDSP_fft only works on integer powers of 2, so he had to choose next integer power of 2 (i.e. 1&amp;lt;&amp;lt;(log2n-1)) instead of plain length for his internal arrays. [3]: you guessed it. fft_zrop(log2n-1, ...) vs. fft_zop(log2n, ...). Half the problem size lol. Now we have vDSP.DiscreteFourierTransform, which wraps vDSP_DFT routines and "calls FFT routines when the size allows it", and works too for interleaved complexes. Just go all DFT, right? if let setup_f = try? vDSP.DiscreteFourierTransform(previous: nil, count: 8, direction: .forward, transformType: .complexComplex, ofType: DSPComplex.self) { // Done forward transformation // and scaled the results with 1/N // How about going reverse? if let setup_r = try? vDSP.DiscreteFourierTransform(previous: setup_f, count: 8, direction: .inverse, transformType: .complexComplex, ofType: DSPComplex.self) { // Error: cannot convert vDSP.DiscreteFourierTransform&amp;lt;DSPComplex&amp;gt; to vDSP.DiscreteFourierTransform&amp;lt;Float&amp;gt; // lolz } } This API appeared in macOS 12. 3 years later nobody have ever noticed. I'm at a loss for words.
4
0
47
1w
Xcode 26 - New Swift 6.2 Concurrency Sendable Closure Problems
I'm running into a seemingly unsolvable compile problem with the new Xcode 26 and Swift 6.2. Here's the issue. I've got this code that was working before: NSAnimationContext.runAnimationGroup({(context) -&gt; Void in context.duration = animated ? 0.5 : 0 clipView.animator().setBoundsOrigin(p) }, completionHandler: { self.endIgnoreFrameChangeEvents() }) It's very simple. The clipView is a scrollView.contentView, and "animated" is a bool, and p is an NSPoint It captures those things, scrolls the clip view (animating if needed) to the point, and then calls a method in self to signal that the animation has completed. I'm getting this error: Call to main actor-isolated instance method 'endIgnoreFrameChangeEvents()' in a synchronous nonisolated context So, I don't understand why so many of my callbacks are getting this error now, when they worked before, but it is easy to solve. There's also an async variation of runAnimationGroup. So let's use that instead: Task { await NSAnimationContext.runAnimationGroup({(context) -&gt; Void in context.duration = animated ? 0.5 : 0 clipView.animator().setBoundsOrigin(p) }) self.endIgnoreFrameChangeEvents() } So, when I do this, then I get a new error. Now it doesn't like the first enclosure. Which it was perfectly happy with before. Here's the error: Sending value of non-Sendable type '(NSAnimationContext) -&gt; Void' risks causing data races Here are the various overloaded definitions of runAnimationGroup: open class func runAnimationGroup(_ changes: (NSAnimationContext) -&gt; Void, completionHandler: (@Sendable () -&gt; Void)? = nil) @available(macOS 10.7, *) open class func runAnimationGroup(_ changes: (NSAnimationContext) -&gt; Void) async @available(macOS 10.12, *) open class func runAnimationGroup(_ changes: (NSAnimationContext) -&gt; Void) The middle one is the one that I'm trying to use. The closure in this overload isn't marked sendable. But, lets try making it sendable now to appease the compiler, since that seems to be what the error is asking for: Task { await NSAnimationContext.runAnimationGroup({ @Sendable (context) -&gt; Void in context.duration = animated ? 0.5 : 0 clipView.animator().setBoundsOrigin(p) }) self.endIgnoreFrameChangeEvents() } So now I get errors in the closure itself. There are 2 errors, only one of which is easy to get rid of. Call to main actor-isolated instance method 'animator()' in a synchronous nonisolated context Call to main actor-isolated instance method 'setBoundsOrigin' in a synchronous nonisolated context So I can get rid of that first error by capturing clipView.animator() outside of the closure and capturing the animator. But the second error, calling setBoundsOrigin(p) - I can't move that outside of the closure, because that is the thing I am animating! Further, any property you're going to me animating in runAnimationGroup is going to be isolated to the main actor. So now my code looks like this, and I'm stuck with this last error I can't eliminate: let animator = clipView.animator() Task { await NSAnimationContext.runAnimationGroup({ @Sendable (context) -&gt; Void in context.duration = animated ? 0.5 : 0 animator.setBoundsOrigin(p) }) self.endIgnoreFrameChangeEvents() } Call to main actor-isolated instance method 'setBoundsOrigin' in a synchronous nonisolated context There's something that I am not understanding here that has changed about how it is treating closures. This whole thing is running synchronously on the main thread anyway, isn't it? It's being called from a MainActor context in one of my NSViews. I would expect the closure in runAnimationGroup would need to be isolated to the main actor, anyway, since any animatable property is going to be marked MainActor. How do I accomplish what I am trying to do here? One last note: There were some new settings introduced at WWDC that supposedly make this stuff simpler - "Approchable Concurrency". In this example, I didn't have that turned on. Turning it on and setting the default to MainActor does not seem to have solved this problem. (All it does is cause hundreds of new concurrency errors in other parts of my code that weren't there before!) This is the last new error in my code (without those settings), but I can't see any way around this one. It's basically the same error as the others I was getting (in the callback closures), except with those I could eliminate the closures by changing APIs.
5
0
143
3d
How to listen for Locale change event in iOS using NSLocale.currentLocaleDidChangeNotification?
I have the following function private func SetupLocaleObserver () { NotificationCenter.default.addObserver ( forName: NSLocale.currentLocaleDidChangeNotification, object: nil, queue: .main ) {_ in print ("Locale changed to: \(Locale.current.identifier)"); } } I call this function inside the viewDidLoad () method of my view controller. The expectation was that whenever I change the system or app-specific language preference, the locale gets changed, and this change triggers my closure which should print "Locale changed to: " on the console. However, the app gets terminated with a SIGKILL whenever I change the language from the settings. So, it is observed that sometimes my closure runs, while most of the times it does not run - maybe the app dies even before the closure is executed. So, the question is, what is the use of this particular notification if the corresponding closure isn't guaranteed to be executed before the app dies? Or am I using it the wrong way?
1
0
48
1w