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
}
}
}
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
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)
}
}
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
}
I generate images with command line apps in Swift on MacOS. Under the prior Xcode/MacOS my code had been running at the same performance for years. Converting to Swift 6 (no code changes) and running on Sequoia, I noticed a massive slowdown. Running Profile, I tracked it down to allow single line:
var values = ContiguousArray<Double>(repeating: 0.0, count: localData.options.count)
count for my current test case is 4, so its allocating 4 doubles at a time, around 40,000 times in this test. This one line takes 42 seconds out of a run time of 52 seconds. With the profile shown as:
26 41.62 s 4.8% 26.00 ms specialized ContiguousArray.init(_uninitializedCount:)
42 41.57 s 4.8% 42.00 ms _ContiguousArrayBuffer.init(_uninitializedCount:minimumCapacity:)
40730 40.93 s 4.7% 40.73 s _swift_allocObject_
68 68.00 ms 0.0% 68.00 ms std::__1::pair<MallocTypeCacheEntry*, unsigned int> swift::ConcurrentReadableHashMap<MallocTypeCacheEntry, swift::LazyMutex>::find<unsigned int>(unsigned int const&, swift::ConcurrentReadableHashMap<MallocTypeCacheEntry, swift::LazyMutex>::IndexStorage, unsigned long, MallocTypeCacheEntry*)
7 130.00 ms 0.0% 7.00 ms swift::swift_slowAllocTyped(unsigned long, unsigned long, unsigned long long)
which is clearly inside the OS allocator somewhere. What happened? Previously this would have taken closer to 8 seconds or so for the entire run.
https://developer.apple.com/forums/thread/768776
Swift concurrency is an important part of my day-to-day job. I created the following document for an internal presentation, and I figured that it might be helpful for others.
If you have questions or comments, put them in a new thread here on DevForums. Use the App & System Services > Processes & Concurrency topic area and tag it with both Swift and Concurrency.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Swift Concurrency Proposal Index
This post summarises the Swift Evolution proposals that went into the Swift concurrency design. It covers the proposal that are implemented in Swift 6.2, plus a few additional ones that aren’t currently available.
The focus is here is the Swift Evolution proposals. For general information about Swift concurrency, see the documentation referenced by Concurrency Resources.
Swift 6.0
The following Swift Evolution proposals form the basis of the Swift 6.0 concurrency design.
SE-0176 Enforce Exclusive Access to Memory
link: SE-0176
notes: This defines the “Law of Exclusivity”, a critical foundation for both serial and concurrent code.
SE-0282 Clarify the Swift memory consistency model ⚛︎
link: SE-0282
notes: This defines Swift’s memory model, that is, the rules about what is and isn’t allowed when it comes to concurrent memory access.
SE-0296 Async/await
link: SE-0296
introduces: async functions, async, await
SE-0297 Concurrency Interoperability with Objective-C
link: SE-0297
notes: Specifies how Swift imports an Objective-C method with a completion handler as an async method. Explicitly allows @objc actors.
SE-0298 Async/Await: Sequences
link: SE-0298
introduces: AsyncSequence, for await syntax
notes: This just defines the AsyncSequence protocol. For one concrete implementation of that protocol, see SE-0314.
SE-0300 Continuations for interfacing async tasks with synchronous code
link: SE-0300
introduces: CheckedContinuation, UnsafeContinuation
notes: Use these to create an async function that wraps a legacy request-reply concurrency construct.
SE-0302 Sendable and @Sendable closures
link: SE-0302
introduces: Sendable, @Sendable closures, marker protocols
SE-0304 Structured concurrency
link: SE-0304
introduces: unstructured and structured concurrency, Task, cancellation, CancellationError, withTaskCancellationHandler(…), sleep(…), withTaskGroup(…), withThrowingTaskGroup(…)
notes: For the async let syntax, see SE-0317. For more ways to sleep, see SE-0329 and SE-0374. For discarding task groups, see SE-0381.
SE-0306 Actors
link: SE-0306
introduces: actor syntax
notes: For actor-isolated parameters and the nonisolated keyword, see SE-0313. For global actors, see SE-0316. For custom executors and the Actor protocol, see SE-0392.
SE-0311 Task Local Values
link: SE-0311
introduces: TaskLocal
SE-0313 Improved control over actor isolation
link: SE-0313
introduces: isolated parameters, nonisolated
SE-0314 AsyncStream and AsyncThrowingStream
link: SE-0314
introduces: AsyncStream, AsyncThrowingStream, onTermination
notes: These are super helpful when you need to publish a legacy notification construct as an async stream. For a simpler API to create a stream, see SE-0388.
SE-0316 Global actors
link: SE-0316
introduces: GlobalActor, MainActor
notes: This includes the @MainActor syntax for closures.
SE-0317 async let bindings
link: SE-0317
introduces: async let syntax
SE-0323 Asynchronous Main Semantics
link: SE-0323
SE-0327 On Actors and Initialization
link: SE-0327
notes: For a proposal to allow access to non-sendable isolated state in a deinitialiser, see SE-0371.
SE-0329 Clock, Instant, and Duration
link: SE-0329
introduces: Clock, InstantProtocol, DurationProtocol, Duration, ContinuousClock, SuspendingClock
notes: For another way to sleep, see SE-0374.
SE-0331 Remove Sendable conformance from unsafe pointer types
link: SE-0331
SE-0337 Incremental migration to concurrency checking
link: SE-0337
introduces: @preconcurrency, explicit unavailability of Sendable
notes: This introduces @preconcurrency on declarations, on imports, and on Sendable protocols. For @preconcurrency conformances, see SE-0423.
SE-0338 Clarify the Execution of Non-Actor-Isolated Async Functions
link: SE-0338
note: This change has caught a bunch of folks by surprise and there’s a discussion underway as to whether to adjust it.
SE-0340 Unavailable From Async Attribute
link: SE-0340
introduces: noasync availability kind
SE-0343 Concurrency in Top-level Code
link: SE-0343
notes: For how strict concurrency applies to global variables, see SE-0412.
SE-0374 Add sleep(for:) to Clock
link: SE-0374
notes: This builds on SE-0329.
SE-0381 DiscardingTaskGroups
link: SE-0381
introduces: DiscardingTaskGroup, ThrowingDiscardingTaskGroup
notes: Use this for task groups that can run indefinitely, for example, a network server.
SE-0388 Convenience Async[Throwing]Stream.makeStream methods
link: SE-0388
notes: This builds on SE-0314.
SE-0392 Custom Actor Executors
link: SE-0392
introduces: Actor protocol, Executor, SerialExecutor, ExecutorJob, assumeIsolated(…)
notes: For task executors, a closely related concept, see SE-0417. For custom isolation checking, see SE-0424.
SE-0395 Observation
link: SE-0395
introduces: Observation module, Observable
notes: While this isn’t directly related to concurrency, it’s relationship to Combine, which is an important exising concurrency construct, means I’ve included it in this list.
SE-0401 Remove Actor Isolation Inference caused by Property Wrappers
link: SE-0401, commentary
availability: upcoming feature flag: DisableOutwardActorInference
SE-0410 Low-Level Atomic Operations ⚛︎
link: SE-0410
introduces: Synchronization module, Atomic, AtomicLazyReference, WordPair
SE-0411 Isolated default value expressions
link: SE-0411, commentary
SE-0412 Strict concurrency for global variables
link: SE-0412
introduces: nonisolated(unsafe)
notes: While this is a proposal about globals, the introduction of nonisolated(unsafe) applies to “any form of storage”.
SE-0414 Region based Isolation
link: SE-0414, commentary
notes: To send parameters and results across isolation regions, see SE-0430.
SE-0417 Task Executor Preference
link: SE-0417, commentary
introduces: withTaskExecutorPreference(…), TaskExecutor, globalConcurrentExecutor
notes: This is closely related to the custom actor executors defined in SE-0392.
SE-0418 Inferring Sendable for methods and key path literals
link: SE-0418, commentary
availability: upcoming feature flag: InferSendableFromCaptures
notes: The methods part of this is for “partial and unapplied methods”.
SE-0420 Inheritance of actor isolation
link: SE-0420, commentary
introduces: #isolation, optional isolated parameters
notes: This is what makes it possible to iterate over an async stream in an isolated async function.
SE-0421 Generalize effect polymorphism for AsyncSequence and AsyncIteratorProtocol
link: SE-0421, commentary
notes: Previously AsyncSequence used an experimental mechanism to support throwing and non-throwing sequences. This moves it off that. Instead, it uses an extra Failure generic parameter and typed throws to achieve the same result. This allows it to finally support a primary associated type. Yay!
SE-0423 Dynamic actor isolation enforcement from non-strict-concurrency contexts
link: SE-0423, commentary
introduces: @preconcurrency conformance
notes: This adds a number of dynamic actor isolation checks (think assumeIsolated(…)) to close strict concurrency holes that arise when you interact with legacy code.
SE-0424 Custom isolation checking for SerialExecutor
link: SE-0424, commentary
introduces: checkIsolation()
notes: This extends the custom actor executors introduced in SE-0392 to support isolation checking.
SE-0430 sending parameter and result values
link: SE-0430, commentary
introduces: sending
notes: Adds the ability to send parameters and results between the isolation regions introduced by SE-0414.
SE-0431 @isolated(any) Function Types
link: SE-0431, commentary, commentary
introduces: @isolated(any) attribute on function types, isolation property of functions values
notes: This is laying the groundwork for SE-NNNN Closure isolation control. That, in turn, aims to bring the currently experimental @_inheritActorContext attribute into the language officially.
SE-0433 Synchronous Mutual Exclusion Lock 🔒
link: SE-0433
introduces: Mutex
SE-0434 Usability of global-actor-isolated types
link: SE-0434, commentary
availability: upcoming feature flag: GlobalActorIsolatedTypesUsability
notes: This loosen strict concurrency checking in a number of subtle ways.
Swift 6.1
Swift 6.1 has the following additions.
Vision: Improving the approachability of data-race safety
link: vision
SE-0442 Allow TaskGroup’s ChildTaskResult Type To Be Inferred
link: SE-0442, commentary
notes: This represents a small quality of life improvement for withTaskGroup(…) and withThrowingTaskGroup(…).
SE-0449 Allow nonisolated to prevent global actor inference
link: SE-0449, commentary
notes: This is a straightforward extension to the number of places you can apply nonisolated.
Swift 6.2
Xcode 26 beta has two new build settings:
Approachable Concurrency enables the following feature flags: DisableOutwardActorInference, GlobalActorIsolatedTypesUsability, InferIsolatedConformances, InferSendableFromCaptures, and NonisolatedNonsendingByDefault.
Default Actor Isolation controls SE-0466
Swift 6.2, still in beta, has the following additions.
SE-0371 Isolated synchronous deinit
link: SE-0371, commentary
introduces: isolated deinit
notes: Allows a deinitialiser to access non-sendable isolated state, lifting a restriction imposed by SE-0327.
SE-0457 Expose attosecond representation of Duration
link: SE-0457
introduces: attoseconds, init(attoseconds:)
SE-0461 Run nonisolated async functions on the caller’s actor by default
link: SE-0461
availability: upcoming feature flag: NonisolatedNonsendingByDefault
introduces: nonisolated(nonsending), @concurrent
notes: This represents a significant change to how Swift handles actor isolation by default, and introduces syntax to override that default.
SE-0462 Task Priority Escalation APIs
link: SE-0462
introduces: withTaskPriorityEscalationHandler(…)
notes: Code that uses structured concurrency benefits from priority boosts automatically. This proposal exposes APIs so that code using unstructured concurrency can do the same.
SE-0463 Import Objective-C completion handler parameters as @Sendable
link: SE-0463
notes: This is a welcome resolution to a source of much confusion.
SE-0466 Control default actor isolation inference
link: SE-0466, commentary
availability: not officially approved, but a de facto part of Swift 6.2
introduces: -default-isolation compiler flag
notes: This is a major component of the above-mentioned vision document.
SE-0468 Hashable conformance for Async(Throwing)Stream.Continuation
link: SE-0468
notes: This is an obvious benefit when you’re juggling a bunch of different async streams.
SE-0469 Task Naming
link: SE-0469
introduces: name, init(name:…)
SE-0470 Global-actor isolated conformances
link: SE-0470
availability: upcoming feature flag: InferIsolatedConformances
introduces: @SomeActor protocol conformance
notes: This is particularly useful when you want to conform an @MainActor type to Equatable, Hashable, and so on.
SE-0471 Improved Custom SerialExecutor isolation checking for Concurrency Runtime
link: SE-0471
notes: This is a welcome extension to SE-0424.
SE-0472 Starting tasks synchronously from caller context
link: SE-0472
introduces: immediate[Detached](…), addImmediateTask[UnlessCancelled](…),
notes: This introduces the concept of an immediate task, one that initially uses the calling execution context. This is one of those things where, when you need it, you really need it. But it’s hard to summary when you might need it, so you’ll just have to read the proposal (-:
In Progress
The proposals in this section didn’t make Swift 6.2.
SE-0406 Backpressure support for AsyncStream
link: SE-0406
availability: returned for revision
notes: Currently AsyncStream has very limited buffering options. This was a proposal to improve that. This feature is still very much needed, but the outlook for this proposal is hazy. My best guess is that something like this will land first in the Swift Async Algorithms package. See this thread.
SE-NNNN Closure isolation control
link: SE-NNNN
introduces: @inheritsIsolation
availability: not yet approved
notes: This aims to bring the currently experimental @_inheritActorContext attribute into the language officially. It’s not clear how this will play out given the changes in SE-0461.
Revision History
2025-09-02 Updated for the upcoming release Swift 6.2.
2025-04-07 Updated for the release of Swift 6.1, including a number of things that are still in progress.
2024-11-09 First post.
decidePolicyFor delegate method:
import WebKit
@objc extension DocumentationVC
{
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
Being called just alright in swift 5 minimal concurrency.
Raising concurrency to complete with swift 5 or swift 6. Changing the code to avoid warnings:
@preconcurrency import WebKit
@objc extension DocumentationVC
{
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
The delegate method is not being called. Changing back to swift 5 concurrency minimal - it is called.
Looking at WKNavigationDelegate:
WK_SWIFT_UI_ACTOR
@protocol WKNavigationDelegate <NSObject>
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(WK_SWIFT_UI_ACTOR void (^)(WKNavigationActionPolicy))decisionHandler WK_SWIFT_ASYNC(3);
Changing the delegate method to:
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void) {
And it is called across swift 5 concurrency minimal to complete to swift 6.
I thought, the meaning of @preconcurrency import WebKit was to keep the delegate without @MainActor before the (WKNavigationActionPolicy) still matching regardless the swift concurrency mode?
My point is - this can introduce hidden breaking changes? I didn't see this documented anyhow at: https://www.swift.org/migration/documentation/migrationguide/.
decidePolicyFor is an optional method - so if signature 'mismatches' - there will be no warning on not-implementing the delegate method.
How do we catch or diagnose irregularities like this? Is it something @preconcurrency import WebKit should be ensuring and it is not?
Is this delegate mismatch a bug on swift side or something we should be taking care of while migrating? If it is on us, how do we diagnose these potential mismatches?
I have the following TaskExecutor code in Swift 6 and is getting the following error:
//Error
Passing closure as a sending parameter risks causing data races between main actor-isolated code and concurrent execution of the closure.
May I know what is the best way to approach this?
This is the default code generated by Xcode when creating a Vision Pro App using Metal as the Immersive Renderer.
Renderer
@MainActor
static func startRenderLoop(_ layerRenderer: LayerRenderer, appModel: AppModel) {
Task(executorPreference: RendererTaskExecutor.shared) { //Error
let renderer = Renderer(layerRenderer, appModel: appModel)
await renderer.startARSession()
await renderer.renderLoop()
}
}
final class RendererTaskExecutor: TaskExecutor {
private let queue = DispatchQueue(label: "RenderThreadQueue", qos: .userInteractive)
func enqueue(_ job: UnownedJob) {
queue.async {
job.runSynchronously(on: self.asUnownedSerialExecutor())
}
}
func asUnownedSerialExecutor() -> UnownedTaskExecutor {
return UnownedTaskExecutor(ordinary: self)
}
static let shared: RendererTaskExecutor = RendererTaskExecutor()
}
I ran into a problem, I have a recursive function in which Data type objects are temporarily created, because of this, the memory expands until the entire recursion ends. It would just be fixed using autoreleasepool, but it can't be used with async await, and I really don't want to rewrite the code for callbacks. Is there any option to use autoreleasepool with async await functions? (I Googled one option, that the Task already contains its own autoreleasepool, and if you do something like that, it should work, but it doesn't, the memory is still growing)
func autoreleasepool<Result>(_ perform: @escaping () async throws -> Result) async throws -> Result {
try await Task {
try await perform()
}.value
}
Given the below code with Swift 6 language mode, Xcode 16.2
If running with iOS 18+: the app crashes due to _dispatch_assert_queue_fail
If running with iOS 17 and below: there is a warning: warning: data race detected: @MainActor function at Swift6Playground/PublishedValuesView.swift:12 was not called on the main thread
Could anyone please help explain what's wrong here?
import SwiftUI
import Combine
@MainActor
class PublishedValuesViewModel: ObservableObject {
@Published var count = 0
@Published var content: String = "NA"
private var cancellables: Set<AnyCancellable> = []
func start() async {
let publisher = $count
.map { String(describing: $0) }
.removeDuplicates()
for await value in publisher.values {
content = value
}
}
}
struct PublishedValuesView: View {
@ObservedObject var viewModel: PublishedValuesViewModel
var body: some View {
Text("Published Values: \(viewModel.content)")
.task {
await viewModel.start()
}
}
}
Considering below dummy codes:
@MainActor var globalNumber = 0
@MainActor
func increase(_ number: inout Int) async {
// some async code excluded
number += 1
}
class Dummy: @unchecked Sendable {
@MainActor var number: Int {
get { globalNumber }
set { globalNumber = newValue }
}
@MainActor
func change() async {
await increase(&number) //Actor-isolated property 'number' cannot be passed 'inout' to 'async' function call
}
}
I'm not really trying to make an increasing function like that, this is just an example to make everything happen. As for why number is a computed property, this is to trigger the actor-isolated condition (otherwise, if the property is stored and is a value type, this condition will not be triggered).
Under these conditions, in function change(), I got the error: Actor-isolated property 'number' cannot be passed 'inout' to 'async' function call.
My question is: Why Actor-isolated property cannot be passed 'inout' to 'async' function call? What is the purpose of this design? If this were allowed, what problems might it cause?
I've narrowed down my question after many rabbit holes - how can C++ code open any view in Swift. I can call functions in swift from C++ (works great), but not async or main actor (or actor at all) functions. And if I'm not mistaken all views are actors if not main actors? When calling from C+ I think its necessary that the first view be the main actor?
I've implemented the code from the WWDC23 C++ interop video (Zoe's image picker) where I made a view in a struct, and just want to call it and let the view do the work.
The compiler immediately gives me 'cannot expose main actors to C++'. If I'm not mistaken, doesn't this block the opening of any kind of swift view from C++? Hopefully I'm missing something obvious, which is likely :)
In Zoe's code was his entry point into the program still Swift and not actually C++ app?
Thanks!
Thanks!
Topic:
Programming Languages
SubTopic:
Swift
We would like to show a user-friendly message but can not.
Description:
When attempting to create a duplicate passkey using the ASAuthrorizationController in iOS, the Face ID authentication times out SDK does not return a timeout specific error. Instead, it directly returns an error stating that duplicate passkey cannot be created.
SDK to first handle the FaceID timeout case and provide a distinct timeout error so we can gracefully manage this scenario before the duplicate passkey validation occurs.
Steps to Reproduce:
Implement passkey creation flow using ASAuthorizationController.
Attempt to register a duplicate passkey (e.g., using the same user ID and challenge).
Let FaceID prompt timeout (do not interact with the authentication prompt).
Topic:
Programming Languages
SubTopic:
Swift
I'm encountering an issue where certain images are not displaying on some iOS devices, while the same code works perfectly on others. There’s no error or crash — just some images fail to load or display. I've confirmed the image URLs and formats are correct.
Has anyone faced a similar issue or could suggest what might be causing this inconsistent behavior?
Thanks in advance!
Topic:
Programming Languages
SubTopic:
Swift
My framework has private Objective-C API that is only used within the framework. It should not be exposed in the public interface (so it shouldn't be imported in the umbrella header).
To expose this API to Swift that's within the framework only the documentation seems to indicate that this needs to be imported in the umbrella header?
Import Code Within a Framework Target
To use the Objective-C declarations in files in the same framework target as your Swift code, configure an umbrella header as follows:
1.Under Build Settings, in Packaging, make sure the Defines Module setting for the framework target is set to Yes.
2.In the umbrella header, import every Objective-C header you want to expose to Swift.
Swift sees every header you expose publicly in your umbrella header. The contents of the Objective-C files in that framework are automatically available from any Swift file within that framework target, with no import statements. Use classes and other declarations from your Objective-C code with the same Swift syntax you use for system classes.
I would imagine that there must be a way to do this?
I'll describe my crash with an example, looking for some insights into the reason why this is happening.
@objc public protocol LauncherContainer {
var launcher: Launcher { get }
}
@objc public protocol Launcher: UIViewControllerTransitioningDelegate {
func initiateLaunch(url: URL, launchingHotInstance: Bool)
}
@objc final class LauncherContainer: NSObject, LauncherContainer, TabsContentCellTapHandler {
...
init(
...
) {
...
super.init()
}
...
//
// ContentCellTapHandler
//
public func tabContentCellItemDidTap(
tabId: String
) {
...
launcher.initiateNewTabNavigation(
tabId: tabId // Crash happens here
)
}
public class Launcher: NSObject, Launcher, FooterPillTapHandler {
public func initiateNewTabNavigation(tabId: String) {
...
}
}
public protocol TabsContentCellTapHandler: NSObject {
func tabContentCellItemDidTap(
tabId: String,
}
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?
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.
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.
Hey all!
in my personal quest to make future proof apps moving to Swift 6, one of my app has a problem when setting an artwork image in MPNowPlayingInfoCenter
Here's what I'm using to set the metadata
func setMetadata(title: String? = nil, artist: String? = nil, artwork: String? = nil) async throws {
let defaultArtwork = UIImage(named: "logo")!
var nowPlayingInfo = [
MPMediaItemPropertyTitle: title ?? "***",
MPMediaItemPropertyArtist: artist ?? "***",
MPMediaItemPropertyArtwork: MPMediaItemArtwork(boundsSize: defaultArtwork.size) { _ in
defaultArtwork
}
] as [String: Any]
if let artwork = artwork {
guard let url = URL(string: artwork) else { return }
let (data, response) = try await URLSession.shared.data(from: url)
guard (response as? HTTPURLResponse)?.statusCode == 200 else { return }
guard let image = UIImage(data: data) else { return }
nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in
image
}
}
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
the app crashes when hitting
MPMediaItemPropertyArtwork: MPMediaItemArtwork(boundsSize: defaultArtwork.size) { _ in
defaultArtwork
}
or
nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in
image
}
commenting out these two make the app work again.
Again, no clue on why.
Thanks in advance
I'm struggling to convert Swift 5 to Swift 6.
As advised in doc, I first turned strict concurrency ON. I got no error.
Then, selected swift6… and problems pop up.
I have a UIViewController with
IBOutlets: eg a TextField.
computed var eg duree
func using UNNotification: func userNotificationCenter
I get the following error in the declaration line of the func userNotificationCenter:
Main actor-isolated instance method 'userNotificationCenter(_:didReceive:withCompletionHandler:)' cannot be used to satisfy nonisolated requirement from protocol 'UNUserNotificationCenterDelegate'
So, I declared the func as non isolated.
This func calls another func func2, which I had also to declare non isolated.
Then I get error on the computed var used in func2
Main actor-isolated property 'duree' can not be referenced from a nonisolated context
So I declared duree as nonsilated(unsafe).
Now comes the tricky part.
The computed var references the IBOutlet dureeField
if dureeField.text == "X"
leading to the error
Main actor-isolated property 'dureeField' can not be referenced from a nonisolated context
So I finally declared the class as mainActor and the textField as nonisolated
@IBOutlet nonisolated(unsafe) weak var dureeField : UITextField!
That silences the error (but declaring unsafe means I get no extra robustness with swift6) just to create a new one when calling dureeField.text:
Main actor-isolated property 'text' can not be referenced from a nonisolated context
Question: how to address properties inside IBOutlets ? I do not see how to declare them non isolated and having to do it on each property of each IBOutlet would be impracticable.
The following did work, but will make code very verbose:
if MainActor.assumeIsolated({dureeField.text == "X"}) {
So I must be missing something.