A method in my app now requires the override keyword when compiling with Xcode 26 beta / iOS 26 SDK, but if I add it, the current official Xcode 16.4 (iOS 18 SDK) throws a compile error. It's about 'toggleSidebar(_:)' in UIViewController.
The problem is:
Apple expects our apps to be ready for iOS 26 launch this fall, so I need to be actively developing and testing in the Xcode 26 beta now.
At the same time, I still need to submit updates to the App Store using the current official Xcode 16.4 until iOS 26 officially launches.
I'm using a single .xcodeproj file and can't keep manually adding/removing -DIOS_SDK_26_OR_LATER in Build Settings multiple times a day.
How to fix it and why isn't there a straightforward #if sdk(>=26.0) type of check for compile-time in Swift?
It's really frustrating to manage this override conflict.
Swift
RSS for tagSwift 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
My experience with Swift 6 strict concurrency so far doesn't match my understanding of implicit MainActor isolation semantics.
This is a cross-post from StackOverflow. I will link answers between both forums.
TL;DR
Build succeeds when testing a struct declared in the test module, but fails when the struct is moved to the main module:
Main actor-isolated property … cannot be accessed from outside the actor.
Steps to reproduce
Open up Xcode 26 beta 2 on macOS 26 (probably also ok on current stables).
Create a new Swift app with Swift testing, no storage. Call it WhatTheSwift.
Set the Swift Language Version on all three targets to Swift 6.
Update the default test file to be this:
import Testing
@testable import WhatTheSwift
struct WhatTheSwiftTests {
@Test func example() async throws {
let thing = Thing(foo: "bar")
#expect(thing.foo == "bar")
}
}
struct Thing {
let foo: String
}
That should build fine, and the tests should pass.
Now, move the Thing declaration into its own Thing.swift file in the WhatTheSwift module, and try running the test again. You should see this:
Observations
Marking the test @MainActor allows the test to pass, suggesting the compiler actually wants to isolate Thing.foo to the main actor.
My question
Why? And why only when Thing is in a different module?
While editing the search text using the external keyboard (with VoiceOver on), if I try to navigate the to List using the keyboard, the focus jumps back to the search field immediately, preventing selection of list items. It's important to note that the voiceover navigation alone without a keyboard works as expected.
It’s as if the List never gains focus—every attempt to move focus lands back on the search field.
The code:
struct ContentView: View {
@State var searchText = ""
let items = ["Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig", "Grape"]
var filteredItems: [String] {
if searchText.isEmpty {
return items
} else {
return items.filter { $0.localizedCaseInsensitiveContains(searchText) }
}
}
var body: some View {
if #available(iOS 16.0, *) {
NavigationStack {
List(filteredItems, id: \.self) { item in
Text(item)
}
.navigationTitle("Fruits")
.searchable(text: $searchText)
}
} else {
NavigationView {
List(filteredItems, id: \.self) { item in
Text(item)
}
.navigationTitle("Fruits")
.searchable(text: $searchText)
}
}
}
}
I’m updating my app’s alternate icons using UIApplication.shared.setAlternateIconName, and I noticed that in iOS 26, Xcode now supports the new .icon file format for App Icons.
Is it possible to reference .icon files directly for alternate icons?
Or does setAlternateIconName still only support traditional .png assets inside the AppIcon set?
I couldn’t find any documentation confirming this either way, and I want to ensure compatibility with the new format while supporting alternate icons.
Any clarification or Apple documentation link would be greatly appreciated!
I have this build error with Xcode 26 beta 2:
var asset:AVURLAsset?
func loadAsset() {
let assetURL = URL.documentsDirectory
.appendingPathComponent("sample.mov")
asset = AVURLAsset(url: assetURL, options: [AVURLAssetPreferPreciseDurationAndTimingKey: true])
/*Error: Type of expression is ambiguous without a type annotation */
if let result = try? await asset?.load(.tracks, .isPlayable, .isComposable) {
}
}
Is there an issue with try? in the new Swift compiler?
Error: Type of expression is ambiguous without a type annotation
Hi,
in our Xcode project we have a Tooling package, which defines build tool plugins for generating compile time safe constants for our localization strings as well as assets using swiftgen.
This is working very well in Xcode 16, but fails in Xcode 26 beta 1 and beta 2 as well.
The failure is specifically:
unsupported configuration: the aggregate target 'Localization' has package dependencies, but targets that build for different platforms depend on it.
I've reduced this to a minimal sample project, which you can find here.. To reproduce: Open the Repro workspace, that is attached in Xcode. Try to build TestyPackage. You'll see the error.
I've filed this bug during WWDC week, but no feedback yet and no solution in Xcode 26 beta 2. Here's the feedback number, in case you have this too and want to file a duplicate: FB17934050.
Does anyone else have this issue and perhaps a solution?
Hi all,
I'm developing a standalone SwiftUI watchOS app (no iOS host or extension), targeting watchOS 11.5, and running into persistent connection issues with Xcode.
Xcode rarely detects my Apple Watch (Series 7, watchOS 11.5)
Sometimes it appears nested under the iPhone; most of the time, it doesn’t
Errors include:
"OS version is lower than the deployment target" (both are 11.5)
"Unable to install... device not supported"
"Connection error 4000", "Tunnel timeout error 1001"
"Ensure Wi-Fi is enabled on both machines" (Wi-Fi is on and on the same network)
Once in a while, the app does install, but mostly I’m blocked.
What I’ve Tried
Verified pairing and trust
Cleaned builds, nuked Derived Data and caches
Reset iPhone privacy settings
Removed and re-added my Apple ID
Used xcrun xctrace list devices (watch inconsistently appears)
Despite this, the app only installs about 5% of the time. Testing (or even running) on real hardware is nearly impossible, and has become incredibly frustrating for me.
Any help or insights would be much appreciated.
When using the new RealityKit Manipulation Component on Entities, indirect input will never translate the entity - no matter what settings are applied. Direct manipulation works as expected for both translation and rotation.
Is this intended behaviour? This is different from how indirect manipulation works on Model3D. How else can we get translation from this component?
visionOS 26 Beta 2
Build from macOS 26 Beta 2 and Xcode 26 Beta 2
Attached is replicable sample code, I have tried this in other projects with the same results.
var body: some View {
RealityView { content in
// Add the initial RealityKit content
if let immersiveContentEntity = try? await Entity(named: "MovieFilmReel", in: reelRCPBundle) {
ManipulationComponent.configureEntity(immersiveContentEntity, allowedInputTypes: .all, collisionShapes: [ShapeResource.generateBox(width: 0.2, height: 0.2, depth: 0.2)])
immersiveContentEntity.position.y = 1
immersiveContentEntity.position.z = -0.5
var mc = ManipulationComponent()
mc.releaseBehavior = .stay
immersiveContentEntity.components.set(mc)
content.add(immersiveContentEntity)
}
}
}
I’m an amateur developer working on a free utility for composers/producers, for which the macOS release needs to create and name RTP-MIDI sessions in Audio MIDI Setup from the command line (so I can ship a small C helper instead of telling users to click through the UI). Here’s what I’ve tried so far, without luck:
• Plist hacks: Injecting entries into ~/Library/Audio/MIDI Configurations/*.mcfg works when AMS is closed, but AMS immediately locks and reverts my changes when it’s open.
• CoreMIDI C API: I can create virtual ports with MIDISourceCreate, but attempting MIDIObjectGetDataProperty on the apple.midirtp.session plugin always returns err –10836.
• Obj-C & Swift: Loading MIDINetworkSession and calling defaultSession, init, setNetworkName: and setting enabled = YES doesn’t produce a new session object in the Network panel.
• dlopen/dlsym: I extracted the real CoreMIDI binary out of the dyld shared cache and tried binding _MIDINetworkSessionCreate, _SetName, _SetEnabled, etc., but all the symbols come back null or my tool segfaults.
• Plugin registration: I’ve pulled the factory UUID (70C9C5EA-7C65-11D8-B317-000393A34B5A) from /System/Library/Extensions/AppleMIDIRTPDriver.plugin/Contents/Info.plist and called CFPlugInRegisterFactories, but it still never exposes the session-creation calls.
At this point I’m convinced I’m either loading the wrong binary or missing one critical step in registering the RTP-MIDI plugin’s private API. Can anyone point me to:
The exact path of the dylib or bundle that actually exports the MIDINetworkSessionCreate/MIDINetworkSessionSetName/MIDINetworkSessionSetEnabled symbols?
A minimal working snippet (C or Obj-C) that reliably creates and names a Network-MIDI session?
Any pointers, sample code, or even ideas about where Apple hides this functionality on macOS 15 would be hugely appreciated. Thanks!
I have my project running perfectly fine on Xcode 16. However, in Xcode 26 it doesn't build due to an error that I do not understand. I have three files that pertain to this error:
// FriendListResponse.swift
import Foundation
struct FriendListResponse: Decodable {
var friendships: [Friendship]
var collections: [FriendCollection]
}
// Friendship.swift
import Foundation
struct Friendship: Decodable {
var createdAt: String
var friendId: Int
var friendUserId: Int // user ID of the friend
var friendUsername: String
var id: Int
var tagNames: [String]
}
// FriendCollection.swift
struct FriendCollection: Decodable {
var id: Int
var permalink: String
var tagNames: [String]
var title: String
}
On the first file, FriendListResponse.swift, I am the simple error message "circular reference." I do not understand how these self-contained structs could create a circular reference. Although I have other data types in my project, none of them are even referenced in these files except for Friendship and FriendCollection.
The FriendListResponse is a struct that is created from JSON values that are fetched from an API. This is the function that fetches the JSON:
public static func listFriends(username: String) async throws -> [Friendship] {
let data = try await sendGETRequest(
url: "people/\(username)/friends/list.json"
)
print(String(data: data, encoding: .utf8)!)
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let wrapper = try decoder.decode(FriendListResponse.self, from: data)
return wrapper.friendships
}
// Note: the function sendGETRequest is just
// a function that I have created that takes a set
// of parameters and returns a data object
// using the HTTP GET protocol. I don't think
// that it is related to this issue. However, if you
// think that it is, I can share the code for that.
This error has also happened in a few other cases within contained networks of my data structure.
I do not know why this error is only appearing once I launch Xcode 26 beta with my project files. I would think that this error also would appear in Xcode 16.4.
Any help would be greatly appreciated in my process to compile my project on Xcode 26!
Hello everyone, I think I've discovered a bug in JSONDecoder and I'd like to get a quick sanity-check on this, as well as hopefully some ideas to work around the issue.
When attempting to decode a Decodable struct from JSON using JSONDecoder, the decoder throws an error when it encounters a dictionary that is keyed by an enum and somehow seems to think that the enum is an Array<Any>.
Here's a minimal reproducible example:
let jsonString = """
{
"variations": {
"plural": "tests",
"singular": "test"
}
}
"""
struct Json: Codable {
let variations: [VariationKind: String]
}
enum VariationKind: String, Codable, Hashable {
case plural = "plural"
case singular = "singular"
}
and then the actual decoding:
let json = try JSONDecoder().decode(
Json.self,
from: jsonString.data(using: .utf8)!
)
print(json)
The expected result would of course be the following:
Json(
variations: [
VariationKind.plural: "tests",
VariationKind.singular: "test"
]
)
But the actual result is an error:
Swift.DecodingError.typeMismatch(
Swift.Array<Any>,
Swift.DecodingError.Context(
codingPath: [
CodingKeys(stringValue: "variations", intValue: nil)
],
debugDescription: "Expected to decode Array<Any> but found a dictionary instead.",
underlyingError: nil
)
)
So basically, the JSONDecoder tries to decode Swift.Array<Any> but encounters a dictionary (duh), and I have no idea why this is happening. There are literally no arrays anywhere, neither in the actual JSON string, nor in any of the Codable structs.
Curiously, if I change the dictionary from [VariationKind: String] to [String: String], everything works perfectly.
So something about the enum seems to cause confusion in JSONDecoder. I've tried to fix this by implementing Decodable myself for VariationKind and using a singleValueContainer, but that causes exactly the same error.
Am I crazy, or is that a bug?
Hey everyone,
I’m developing an app for visionOS where I need to display the Apple Vision Pro’s current IP address. For this I’m using the following code, which works for iOS, macOS, and visionOS in the simulator. Only on a real Apple Vision Pro it’s unable to extract an IP. Could it be that visionOS currently doesn’t allow this? Have any of you had the same experience and found a workaround?
var address: String = "no ip"
var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
if getifaddrs(&ifaddr) == 0 {
var ptr = ifaddr
while ptr != nil {
defer { ptr = ptr?.pointee.ifa_next }
let interface = ptr?.pointee
let addrFamily = interface?.ifa_addr.pointee.sa_family
if addrFamily == UInt8(AF_INET) {
if let name: Optional<String> = String(cString: (interface?.ifa_name)!), name == "en0" {
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
getnameinfo(interface?.ifa_addr, socklen_t((interface?.ifa_addr.pointee.sa_len)!), &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST)
address = String(cString: hostname)
}
}
}
freeifaddrs(ifaddr)
}
return address
}
Thanks in advance for any insights or tips!
Best Regards,
David
I'm trying to disable the sleep timer when a button is pressed in my macOS app but the problem is that from the resources I've seen elsewhere the code doesn't work.
The code I'm trying is
UIApplication.shared.isIdleTimerDisabled = true
When I try and run my app I get this error
Cannot find 'UIApplication' in scope
From what I've managed to search for regarding this it appears that UIApplication might be an iOS thing, but how can I adapt this for macOS? I've found some code samples from 5+ years ago but it involves lots of code. Surely, in 2025 macOS can disable sleep mode as easy as iOS, right?
How can I achieve this please?
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?
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.
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?
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)")
}
}
}
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
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)
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?