Discuss Swift.

Swift Documentation

Post

Replies

Boosts

Views

Activity

Why doesn’t getAPI() show up in autocomplete despite having a default implementation in a protocol extension?
I’m working on a project in Xcode 16.2 and encountered an issue where getAPI() with a default implementation in a protocol extension doesn’t show up in autocomplete. Here’s a simplified version of the code: import Foundation public protocol Repository { func getAPI(from url: String?) } extension Repository { public func getAPI(from url: String? = "https://...") { getAPI(from: url) } } final class _Repository: Repository { func getAPI(from url: String?) { // Task... } } let repo: Repository = _Repository() repo.getAPI( // Autocomplete doesn't suggest getAPI() I’ve tried the following without success: • Clean build folder • Restart Xcode • Reindexing Is there something wrong with the code, or is this a known issue with Xcode 16.2? I’d appreciate any insights or suggestions.
0
0
47
7h
DebugDescription macro causing “String Interpolation” warnings
Using the DebugDescription macro to display an optional value produces a “String interpolation produces a debug description for an optional value” build warning. For example: @DebugDescription struct MyType: CustomDebugStringConvertible { let optionalValue: String? public var debugDescription: String { "Value: \(optionalValue)" } } The DebugDescription macro does not allow (it is an error) "Value: \(String(describing: optionalValue))" or "Value: \(optionalValue ?? "nil")" because “Only references to stored properties are allowed.” Is there a way to reconcile these? I have a build log full of these warnings, obscuring real issues.
0
0
114
3d
indices(where:) Swift Playgrounds Issue: "Cannot call value of non-function type Range<Int>"
Hey there- I'm having a quite interesting bug on Swift Playgrounds. I am trying to run my app with this following code snippet which does not compile on Swift Playgrounds, yet compiles on XCode (note: this is a Swift Playground app) if #available(iOS 18.0, *) { //simple function to get the indices of other items that have the same date as the "date" variable let indices = data!.indices(where: { item in let sameMonth = Calendar.current.component(.month, from: item.time) == Calendar.current.component(.month, from: date) let sameYear = Calendar.current.component(.year, from: item.time) == Calendar.current.component(.year, from: date) let sameDay = Calendar.current.component(.day, from: item.time) == Calendar.current.component(.year, from: date) return sameDay && sameMonth && sameYear }) However, the indices(where:) codeblock seems to stop the app from compiling (ONLY on Swift Playgrounds - it works perfectly fine on XCode). I am getting the following error: Cannot call value of non-function type 'Range<Array<Int>.Index>' (aka 'Range<Int>') Please let me know if you have any insight regarding this issue. -ColoredOwl
2
1
146
5d
Swift6 race warning
I'm trying to fix some Swift6 warnings, this one seems too strict, I'm not sure how to fix it. The variable path is a String, which should be immutable, it's a local variable and never used again inside of the function, but still Swift6 complains about it being a race condition, passing it to the task What should I do here to fix the warning?
4
0
137
6d
Polynomial Coefficients calculation
How can I calculate polynomial coefficients for Tone Curve points: // • Red channel: (0, 0), (60, 39), (128, 128), (255, 255) // • Green channel: (0, 0), (63, 50), (128, 128), (255, 255) // • Blue channel: (0, 0), (60, 47), (119, 119), (255, 255) CIFilter: func colorCrossPolynomial(inputImage: CIImage) -> CIImage? { let colorCrossPolynomial = CIFilter.colorCrossPolynomial() let redfloatArr: [CGFloat] = [1, 1, 1, 1, 0, 0, 0, 0, 0, 0] let greenfloatArr: [CGFloat] = [0, 1, 1, 0, 0, 0, 0, 0, 0, 1] let bluefloatArr: [CGFloat] = [0, 0, 1, 0, 0, 0, 0, 1, 1, 0] colorCrossPolynomial.inputImage = inputImage colorCrossPolynomial.blueCoefficients = CIVector(values: bluefloatArr, count: bluefloatArr.count) colorCrossPolynomial.redCoefficients = CIVector(values: redfloatArr, count: redfloatArr.count) colorCrossPolynomial.greenCoefficients = CIVector(values: greenfloatArr, count: greenfloatArr.count) return colorCrossPolynomial.outputImage }
1
0
144
1w
NSExpression error handling
Context: SwiftUI TextField with a String for simple math using NSExpression. I first prepare the input string to an extent but a malformed input using valid characters still fails, as expected. Let's say preparedExpression is "5--" let expr = NSExpression(format: preparedExpression) gives FAULT: NSInvalidArgumentException: Unable to parse the format string "5-- == 1"; (user info absent) How can I use NSExpression such that either the preparedExpression is pre-tested before asking for actual execution or the error is handled in a polite way that I can use to alert the user to try again. Is there a Swift alternative to NSExpression that I've missed?
3
0
252
2w
error handling - Xcode shows error since Xcode Version > 15
Hello together, since Xcode Version > 15 the following error handling causes following error "Pattern of type 'DecodingError' cannot match 'Never' func getSupportedCountries() async { // fetch all documents from collection "seasons" from firestore let queryCountries = try? await db.collection("countries").getDocuments() if queryCountries != nil { self.countries = (queryCountries!.documents.compactMap({ (queryDocumentSnapshot) -> Country? in let result = Result { try? queryDocumentSnapshot.data(as: Country.self) } switch result { case .success(let country): if let country = country { // A country value was successfully initialized from the DocumentSnapshot self.errorMessage = nil return country } else { // A nil value was successfully initialized from the DocumentSnapshot, // or the DocumentSnapshot was nil self.errorMessage = "Document doesn't exist." return nil } case .failure(let error): // A Country value could not be initialized from the DocumentSnapshot switch error { case DecodingError.typeMismatch(_, let context): self.errorMessage = "\(error.localizedDescription): \(context.debugDescription)" case DecodingError.valueNotFound(_, let context): self.errorMessage = "\(error.localizedDescription): \(context.debugDescription)" case DecodingError.keyNotFound(_, let context): self.errorMessage = "\(error.localizedDescription): \(context.debugDescription)" case DecodingError.dataCorrupted(let key): self.errorMessage = "\(error.localizedDescription): \(key)" default: self.errorMessage = "Error decoding document: \(error.localizedDescription)" } return nil } })) } else { self.errorMessage = "No documents in 'countries' collection" return } } the interesting part of the code where XCODE shows an error is from "switch error" downwards. Does anyone of you have an idea what's wrong? Ay help appreciated ! Thx, Peter
3
0
169
2w
Questions about calculate the square root using Accelerate
I am currently studying the Accelerate library by referring to Apple documentation. Here is the link to the referenced document: https://developer.apple.com/documentation/accelerate/veclib/vforce When I executed the sample code provided at the bottom of the document, I found a case where the results were different. let n = 10_000 let x = (0..&lt;n).map { _ in Float.random(in: 1 ... 10_000) } let y = x.map { return sqrt($0) } and let y = [Float](unsafeUninitializedCapacity: n) { buffer, initializedCount in vForce.sqrt(x, result: &amp;buffer) initializedCount = n } The code below is provided to observe the issue described above. import Accelerate Task { let n = 1//10_000 let x = (0..&lt;n).map { _ in Float(6737.015)//Float.random(in: 1 ... 10_000) } let y = x.map { return sqrt($0) } try? await Task.sleep(nanoseconds: 1_000_000_000) let z = [Float](unsafeUninitializedCapacity: n) { buffer, initializedCount in vForce.sqrt(x, result: &amp;buffer) initializedCount = n } } For a value of 6737.015 when calculating the square root: Using the sqrt(_:) function gives the result 82.07932, While using the vForce.sqrt(_:result:) function gives the result 82.07933. Using a calculator, the value comes out as 82.07932139, which shows that the result from vForce is incorrect. Could you explain the reason behind this difference?
2
0
201
2w
orientation transaction token
Hello Im having an error in swiftUI project of mine. I use fullscreencover to navigate through views. Normally it s been working but one point it doesn't. I go through MainMenu -> SomeOtherView -> GameView -> AfterGameView -> SomeOtherView -> MainMenu. When it comes to mainmenu at last, it s showing main menu for a glimpse of a look and then goes back to GameView. In console an error took my notice. > A new orientation transaction token is being requested while a valid one already exists. reason=Fullscreen transition (dismissing): fromVC=<_TtGC7SwiftUI29PresentationHostingControllerVS_7AnyView_: 0x10795ca00>; toVC=<_TtGC7SwiftUI29PresentationHostingControllerVS_7AnyView_: 0x1071c3400>;; windowOrientation=portrait; sceneOrientation=portrait; existingTransaction=<_UIForcedOrientationTransactionToken: 0x600001804a40; state: active; originalOrientation: portrait (1)> Cant really finding the solution. Need help asap I will release a bug update to Appstore.
0
0
198
2w
WKWebView missing page parts
Hi guys, I've been struggling for a few days with this really weird behaviour. We made an app for our e-commerce website and found out that a part of the product page is missing. For any reason, the header and first blocks of the page and footer are displayed, but then a massive part of the content is missing. This content is not loaded through ajax; that's why I don't understand why it's not displayed. You can see here 2 screenshots of what the page should look like and what the page looks like with WKWebView. I've been inspecting this with Safari; there isn't any blocking error in the console, and html elements are just empty. There is the div with class row and nothing in it. The same website is working perfectly with native Android Webview. If anyone has any clue to find out what's going wrong
0
0
133
2w
How to save a point cloud in the sample code "Capturing depth using the LiDAR camera" with the photoOutput
Hello dear community, I have the sample code from Apple “CapturingDepthUsingLiDAR” to access the LiDAR on my iPhone 12 Pro. My goal is to use the “photo output” function to generate a point cloud from a single image and then save it as a ply file. So far I have tested different approaches to create a .ply file from the depthmap, the intrinsic camera data and the rgba values. Unfortunately, I have had no success so far and the result has always been an incorrect point cloud. My question now is whether there are already approaches to this and whether anyone has any experience with it. Thank you very much in advance!!!
2
0
219
2w
HealthKit permissions not honoring user selection
I'm dealing with a strange bug where I am requesting read access for 'appleExerciseTime' and 'activitySummaryType', and despite enabling both in the permission sheet, they are being set to 'sharingDenied'. I'm writing a Swift Test for making sure permissions are being granted. @Test func PermissionsGranted() { try await self.manager.getPermissions() for type in await manager.allHealthTypes { let status = await manager.healthStore.authorizationStatus(for: type) #expect(status == .sharingAuthorized, "\(type) authorization status is \(status)") } } let healthTypesToShare: Set<HKSampleType> = [ HKQuantityType(.bodyMass), HKQuantityType(.bodyFatPercentage), HKQuantityType(.leanBodyMass), HKQuantityType(.activeEnergyBurned), HKQuantityType(.basalEnergyBurned), HKObjectType.workoutType() ] let allHealthTypes: Set<HKObjectType> = [ HKQuantityType(.bodyMass), HKQuantityType(.bodyFatPercentage), HKQuantityType(.leanBodyMass), HKQuantityType(.activeEnergyBurned), HKQuantityType(.basalEnergyBurned), HKQuantityType(.appleExerciseTime), HKObjectType.activitySummaryType() ] let healthStore = HKHealthStore() func getPermissions() async throws { try await healthStore.requestAuthorization(toShare: self.healthTypesToShare, read: self.allHealthTypes) } After 'getPermissions' runs, the permission sheet shows up on the Simulator, and I accept all. I've double checked that the failing permissions show up on the sheet and are enabled. Then the test fails with: Expectation failed: (status → HKAuthorizationStatus(rawValue: 1)) == (.sharingAuthorized → HKAuthorizationStatus(rawValue: 2)) HKActivitySummaryTypeIdentifier authorization status is HKAuthorizationStatus(rawValue: 1) Expectation failed: (status → HKAuthorizationStatus(rawValue: 1)) == (.sharingAuthorized → HKAuthorizationStatus(rawValue: 2)) HKActivitySummaryTypeIdentifier authorization status is HKAuthorizationStatus(rawValue: 1) With the rawValue of '1' being 'sharingDenied'. All other permissions are granted. Is there a workaround here, or something I'm potentially doing wrong?
1
0
286
2w
Swift/objC combined with Swift/C++ interop
Consider this Swift struct: public struct Example { public func foo(callback: ()->Void) { .... } public func blah(i: Int) { .... } .... } Using Swift/C++ interop, I can create Example objects and call methods like blah. But I can't call foo because Swift/C++ interop doesn't currently support passing closures (right?). On the other hand, Swift/objC does support passing objC blocks to Swift functions. But I can't use that here because Example is a Swift struct, not a class. So I could change it to a class, and update everything to work with reference rather than value semantics; but then I also have to change the objC++ code to create the object and call its methods using objC syntax. I'd like to avoid that. Is there some hack that I can use to make this possible? I'm hoping that I can wrap a C++ std::function in some sort of opaque wrapper and pass that to swift, or something. Thanks for any suggestions!
1
0
265
2w
SwifUI. Short way for using modifier methods
These helper methods allow to use modifier methods in standard for SwiftUI short way. extension View { @inline(__always) func modify(_ block: (_ view: Self) -> some View) -> some View { block(self) } @inline(__always) func modify<V : View, T>(_ block: (_ view: Self, _ data: T) -> V, with data: T) -> V { block(self, data) } } _ DISCUSSION Suppose you have modifier methods: func addBorder(view: some View) -> some View { view.padding().border(Color.red, width: borderWidth) } func highlight(view: some View, color: Color) -> some View { view.border(Color.red, width: borderWidth).overlay { color.opacity(0.3) } } _ Ordinar Decision Your code may be like this: var body: some View { let image = Image(systemName: "globe") let borderedImage = addBorder(view: image) let highlightedImage = highlight(view: borderedImage, color: .red) let text = Text("Some Text") let borderedText = addBorder(view: text) let highlightedText = highlight(view: borderedText, color: .yellow) VStack { highlightedImage highlightedText } } This code doesn't look like standard SwiftUI code. _ Better Decision Described above helper methods modify(:) and modify(:,with:) allow to write code in typical for SwiftUI short way: var body: some View { VStack { Image(systemName: "globe") .modify(addBorder) .modify(highlight, with: .red) Text("Some Text") .modify(addBorder) .modify(highlight, with: .yellow) } }
0
0
267
3w
Animatable AnyInsettableShape
System provides AnyShape type erasure that animates correctly. But system doesn't provide AnyInsettableShape. Here is my implementation of AnyInsettableShape (and AnyAnimatableData that is needed to support animation). Let me know if there is simpler solution. struct AnyInsettableShape: InsettableShape { private let _path: (CGRect) -> Path private let _inset: (CGFloat) -> AnyInsettableShape private let _getAnimatableData: () -> AnyAnimatableData private let _setAnimatableData: (_ data: AnyAnimatableData) -> AnyInsettableShape init<S>(_ shape: S) where S : InsettableShape { _path = { shape.path(in: $0) } _inset = { AnyInsettableShape(shape.inset(by: $0)) } _getAnimatableData = { AnyAnimatableData(shape.animatableData) } _setAnimatableData = { data in guard let otherData = data.rawValue as? S.AnimatableData else { assertionFailure(); return AnyInsettableShape(shape) } var shape = shape shape.animatableData = otherData return AnyInsettableShape(shape) } } var animatableData: AnyAnimatableData { get { _getAnimatableData() } set { self = _setAnimatableData(newValue) } } func path(in rect: CGRect) -> Path { _path(rect) } func inset(by amount: CGFloat) -> some InsettableShape { _inset(amount) } } struct AnyAnimatableData : VectorArithmetic { init<T : VectorArithmetic>(_ value: T) { self.init(optional: value) } private init<T : VectorArithmetic>(optional value: T?) { rawValue = value _scaleBy = { factor in (value != nil) ? AnyAnimatableData(value!.scaled(by: factor)) : .zero } _add = { other in AnyAnimatableData(value! + (other.rawValue as! T)) } _subtract = { other in AnyAnimatableData(value! - (other.rawValue as! T)) } _equal = { other in value! == (other.rawValue as! T) } _magnitudeSquared = { (value != nil) ? value!.magnitudeSquared : .zero } _zero = { AnyAnimatableData(T.zero) } } fileprivate let rawValue: (any VectorArithmetic)? private let _scaleBy: (_: Double) -> AnyAnimatableData private let _add: (_ other: AnyAnimatableData) -> AnyAnimatableData private let _subtract: (_ other: AnyAnimatableData) -> AnyAnimatableData private let _equal: (_ other: AnyAnimatableData) -> Bool private let _magnitudeSquared: () -> Double private let _zero: () -> AnyAnimatableData mutating func scale(by rhs: Double) { self = _scaleBy(rhs) } var magnitudeSquared: Double { _magnitudeSquared() } static let zero = AnyAnimatableData(optional: nil as Double?) @inline(__always) private var isZero: Bool { rawValue == nil } static func + (lhs: AnyAnimatableData, rhs: AnyAnimatableData) -> AnyAnimatableData { guard let (lhs, rhs) = fillZeroTypes(lhs, rhs) else { return .zero } return lhs._add(rhs) } static func - (lhs: AnyAnimatableData, rhs: AnyAnimatableData) -> AnyAnimatableData { guard let (lhs, rhs) = fillZeroTypes(lhs, rhs) else { return .zero } return lhs._subtract(rhs) } static func == (lhs: AnyAnimatableData, rhs: AnyAnimatableData) -> Bool { guard let (lhs, rhs) = fillZeroTypes(lhs, rhs) else { return true } return lhs._equal(rhs) } @inline(__always) private static func fillZeroTypes(_ lhs: AnyAnimatableData, _ rhs: AnyAnimatableData) -> (AnyAnimatableData, AnyAnimatableData)? { switch (!lhs.isZero, !rhs.isZero) { case (true, true): (lhs, rhs) case (true, false): (lhs, lhs._zero()) case (false, true): (rhs._zero(), rhs) case (false, false): nil } } }
0
0
264
3w
AVExportSession in Xcode16 - "exportAsynchronouslyWithCompletionHandler: more than once."
I’m experiencing a crash at runtime when trying to extract audio from a video. This issue occurs on both iOS 18 and earlier versions. The crash is caused by the following error: *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '*** -[AVAssetExportSession exportAsynchronouslyWithCompletionHandler:] Cannot call exportAsynchronouslyWithCompletionHandler: more than once. (0x1851435ec 0x1826dd244 0x1970c09c0 0x214d8f358 0x214d95899 0x190a1c8b9 0x214d8efd9 0x30204cef5 0x302053ab9 0x190a5ae39) libc++abi: terminating due to uncaught exception of type NSException My previous code worked fine, but it's crashing with Swift 6. Does anyone know a solution for this? Previous code: func extractAudioFromVideo(from videoURL: URL, exportHandler: ((AVAssetExportSession, CurrentValueSubject<Float, Never>?) -> Void)? = nil, completion: @escaping (Swift.Result<URL, Error>) -> Void) { let asset = AVAsset(url: videoURL) // Create an AVAssetExportSession to export the audio track guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A) else { completion(.failure(NSError(domain: "com.example.app", code: -1, userInfo: [NSLocalizedDescriptionKey: "Failed to create AVAssetExportSession"]))) return } // Set the output file type and path guard let filename = videoURL.lastPathComponent.components(separatedBy: ["."]).first else { return } let outputURL = VideoUtils.getTempAudioExportUrl(filename) VideoUtils.deleteFileIfExists(outputURL.path) exportSession.outputFileType = .m4a exportSession.outputURL = outputURL let audioExportProgressPublisher = CurrentValueSubject<Float, Never>(0.0) if let exportHandler = exportHandler { exportHandler(exportSession, audioExportProgressPublisher) } // Periodically check the progress of the export session let timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in audioExportProgressPublisher.send(exportSession.progress) } // Export the audio track asynchronously exportSession.exportAsynchronously { switch exportSession.status { case .completed: completion(.success(outputURL)) case .failed: completion(.failure(exportSession.error ?? NSError(domain: "com.example.app", code: -1, userInfo: [NSLocalizedDescriptionKey: "Unknown error occurred while exporting audio"]))) case .cancelled: completion(.failure(NSError(domain: "com.example.app", code: -1, userInfo: [NSLocalizedDescriptionKey: "Export session was cancelled"]))) default: completion(.failure(NSError(domain: "com.example.app", code: -1, userInfo: [NSLocalizedDescriptionKey: "Unknown export session status"]))) } // Invalidate the timer when the export session completes or is cancelled timer.invalidate() } } ## New Code: func extractAudioFromVideo(from videoURL: URL, exportHandler: ((AVAssetExportSession, CurrentValueSubject<Float, Never>?) -> Void)? = nil, completion: @escaping (Swift.Result<URL, Error>) -> Void) { let asset = AVAsset(url: videoURL) // Create an AVAssetExportSession to export the audio track guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A) else { completion(.failure(NSError(domain: "com.example.app", code: -1, userInfo: [NSLocalizedDescriptionKey: "Failed to create AVAssetExportSession"]))) return } // Set the output file type and path guard let filename = videoURL.lastPathComponent.components(separatedBy: ["."]).first else { return } let outputURL = VideoUtils.getTempAudioExportUrl(filename) VideoUtils.deleteFileIfExists(outputURL.path) exportSession.outputFileType = .m4a exportSession.outputURL = outputURL let audioExportProgressPublisher = CurrentValueSubject<Float, Never>(0.0) if let exportHandler { exportHandler(exportSession, audioExportProgressPublisher) } let task = Task { if #available(iOS 18.0, *) { // Handle export for iOS 18 and later let states = exportSession.states(updateInterval: 0.1) for await state in states { switch state { case .pending, .waiting: break case .exporting(progress: let progress): print("Exporting: \(progress.fractionCompleted)") if progress.isFinished { completion(.success(outputURL)) } else if progress.isCancelled { completion(.failure(NSError(domain: "com.example.app", code: -1, userInfo: [NSLocalizedDescriptionKey: "Export session was cancelled"]))) } else { audioExportProgressPublisher.send(Float(progress.fractionCompleted)) } } } try await exportSession.export(to: outputURL, as: .m4a) // Only call export once } else { // Handle export for iOS versions below 18 let publishTimer = Timer.publish(every: 0.1, on: .main, in: .common) .autoconnect() .sink { [weak exportSession] _ in guard let exportSession = exportSession else { return } audioExportProgressPublisher.send(exportSession.progress) } // Only call export once await exportSession.export() // Handle the export session's status switch exportSession.status { case .completed: completion(.success(outputURL)) case .failed: completion(.failure(exportSession.error ?? NSError(domain: "com.example.app", code: -1, userInfo: [NSLocalizedDescriptionKey: "Unknown error occurred while exporting audio"]))) case .cancelled: completion(.failure(NSError(domain: "com.example.app", code: -1, userInfo: [NSLocalizedDescriptionKey: "Export session was cancelled"]))) default: completion(.failure(NSError(domain: "com.example.app", code: -1, userInfo: [NSLocalizedDescriptionKey: "Unknown export session status"]))) } // Invalidate the timer when the export session completes or is cancelled publishTimer.cancel() } } task.cancel() }
0
0
227
3w
Timeline refresh issue for widget on ios 18.2
I use AppIntent to trigger a widget refresh, Appint is used on Button or Toggle,as follows var isAudibleArming = false struct SoundAlarmIntent: AppIntent { static var title: LocalizedStringResource = "SoundAlarmIntent" func perform() async throws -> some IntentResult { isAudibleArming = true return .result() } } func timeline( for configuration: DynamicIntentWidgetPersonIntent, in context: Context ) async -> Timeline { var entries: [Entry] = [] let currentDate = Date() let entry = Entry(person: person(for: configuration)) entries.append(entry) if isAudibleArming { let entry2 = Entry(person: Person(name: "Friend4", dateOfBirth: currentDate.adding(.second, value: 6))) entries.append(entry2) } return .init(entries: entries, policy: .never) } The timeline function fires, with entry corresponding to view1 and entry2 corresponding to view2. I expect to show view1 immediately and view2 6 seconds later. You get the correct response on iOS17. But the 6 second delay function on the discovery code in iOS18.2 takes effect immediately, view1 flashes, view2 appears immediately instead of waiting 6 seconds to appear.
7
0
341
3w