Within my app, I have:
for try await update in LockedCameraCaptureManager.shared.sessionContentUpdates {
It seems that the first time my app opens from LockedCameraCapture (after enabling camera permissions etc...) this update is never called and the user will not see their capture (.added or .initial)
If I then try to take another picture/video through my LockedCameraCapture control, it takes the video, opens the app as before, but this time sessionContentUpdates is called twice, once for the first video and once for the second video!
After that it doesn't seem to occur again and all works perfectly!
My device is: iPhone 16 Pro Max, iOS 18.2 developer beta
Has anyone experienced this?
Post
Replies
Boosts
Views
Activity
Why assigning function.formula = formula does not change function.formula to formula in one go? It's always late one change behind.
struct CustomFunction has defined
.formula as @MainActor.
I feel stupid.
There is a part of code:
struct CustomFormulaView: View {
@Binding var function: CustomFunction
@State var testFormula: String = ""
@EnvironmentObject var manager: Manager
....
.onChange(of: testFormula) {
debugPrint("change of test formula: \(testFormula)")
switch function.checkFormula(testFormula, on: manager.finalSize) {
case .success(let formula):
debugPrint("before Change: \(function.formula)")
function.formula = formula // Nothing happens
debugPrint("Test formula changed: \(testFormula)")
debugPrint("set to success: \(formula)")
debugPrint("what inside function? \(function.formula)")
Task {
//Generate Image
testImage = await function.image(
size: testImageSize),
simulate: manager.finalSize)
debugPrint("test image updated for: \(function.formula)")
}
....
and it produces this output when changed from 0.5 to 1.0
Debug: change of test formula: 1.0
Debug: before Change: 0.5
Debug: Test formula changed: 1.0
Debug: set to success: 1.0
Debug: what inside function? 0.5
Debug: test image updated for: 0.5
0.5 is an old value, function.formula should be 1.0
WT??
Hi, I'm trying to modify the ScreenCaptureKit Sample code by implementing an actor for Metal rendering, but I'm experiencing issues with frame rendering sequence.
My app workflow is:
ScreenCapture -> createFrame -> setRenderData
Metal draw callback -> renderAsync (getData from renderData)
I've added timestamps to verify frame ordering, I also using binarySearch to insert the frame with timestamp, and while the timestamps appear to be in sequence, the actual rendering output seems out of order.
// ScreenCaptureKit sample
func createFrame(for sampleBuffer: CMSampleBuffer) async {
if let surface: IOSurface = getIOSurface(for: sampleBuffer) {
await renderer.setRenderData(surface, timeStamp: sampleBuffer.presentationTimeStamp.seconds)
}
}
class Renderer {
...
func setRenderData(surface: IOSurface, timeStamp: Double) async {
_ = await renderSemaphore.getSetBuffers(
isGet: false,
surface: surface,
timeStamp: timeStamp
)
}
func draw(in view: MTKView) {
Task {
await renderAsync(view)
}
}
func renderAsync(_ view: MTKView) async {
guard await renderSemaphore.beginRender() else { return }
guard let frame = await renderSemaphore.getSetBuffers(
isGet: true, surface: nil, timeStamp: nil
) else {
await renderSemaphore.endRender()
return }
guard let texture = await renderSemaphore.getRenderData(
device: self.device,
surface: frame.surface) else {
await renderSemaphore.endRender()
return
}
guard let commandBuffer = _commandQueue.makeCommandBuffer(),
let renderPassDescriptor = await view.currentRenderPassDescriptor,
let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor) else {
await renderSemaphore.endRender()
return
}
// Shaders ..
renderEncoder.endEncoding()
commandBuffer.addCompletedHandler() { @Sendable (_ commandBuffer)-> Swift.Void in
updateFPS()
}
// commit frame in actor
let success = await renderSemaphore.commitFrame(
timeStamp: frame.timeStamp,
commandBuffer: commandBuffer,
drawable: view.currentDrawable!
)
if !success {
print("Frame dropped due to out-of-order timestamp")
}
await renderSemaphore.endRender()
}
}
actor RenderSemaphore {
private var frameBuffers: [FrameData] = []
private var lastReadTimeStamp: Double = 0.0
private var lastCommittedTimeStamp: Double = 0
private var activeTaskCount = 0
private var activeRenderCount = 0
private let maxTasks = 3
private var textureCache: CVMetalTextureCache?
init() {
}
func initTextureCache(device: MTLDevice) {
CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, device, nil, &self.textureCache)
}
func beginRender() -> Bool {
guard activeRenderCount < maxTasks else { return false }
activeRenderCount += 1
return true
}
func endRender() {
if activeRenderCount > 0 {
activeRenderCount -= 1
}
}
func setTextureLoaded(_ loaded: Bool) {
isTextureLoaded = loaded
}
func getSetBuffers(isGet: Bool, surface: IOSurface?, timeStamp: Double?) -> FrameData? {
if isGet {
if !frameBuffers.isEmpty {
let frame = frameBuffers.removeFirst()
if frame.timeStamp > lastReadTimeStamp {
lastReadTimeStamp = frame.timeStamp
print(frame.timeStamp)
return frame
}
}
return nil
} else {
// Set
let frameData = FrameData(
surface: surface!,
timeStamp: timeStamp!
)
// insert to the right position
let insertIndex = binarySearch(for: timeStamp!)
frameBuffers.insert(frameData, at: insertIndex)
return frameData
}
}
private func binarySearch(for timeStamp: Double) -> Int {
var left = 0
var right = frameBuffers.count
while left < right {
let mid = (left + right) / 2
if frameBuffers[mid].timeStamp > timeStamp {
right = mid
} else {
left = mid + 1
}
}
return left
}
// for setRenderDataNormalized
func tryEnterTask() -> Bool {
guard activeTaskCount < maxTasks else { return false }
activeTaskCount += 1
return true
}
func exitTask() {
activeTaskCount -= 1
}
func commitFrame(timeStamp: Double,
commandBuffer: MTLCommandBuffer,
drawable: MTLDrawable) async -> Bool {
guard timeStamp > lastCommittedTimeStamp else {
print("Drop frame at commit: \(timeStamp) <= \(lastCommittedTimeStamp)")
return false
}
commandBuffer.present(drawable)
commandBuffer.commit()
lastCommittedTimeStamp = timeStamp
return true
}
func getRenderData(
device: MTLDevice,
surface: IOSurface,
depthData: [Float]
) -> (MTLTexture, MTLBuffer)? {
let _textureName = "RenderData"
var px: Unmanaged<CVPixelBuffer>?
let status = CVPixelBufferCreateWithIOSurface(kCFAllocatorDefault, surface, nil, &px)
guard status == kCVReturnSuccess, let screenImage = px?.takeRetainedValue() else {
return nil
}
CVMetalTextureCacheFlush(textureCache!, 0)
var texture: CVMetalTexture? = nil
let width = CVPixelBufferGetWidthOfPlane(screenImage, 0)
let height = CVPixelBufferGetHeightOfPlane(screenImage, 0)
let result2 = CVMetalTextureCacheCreateTextureFromImage(
kCFAllocatorDefault,
self.textureCache!,
screenImage,
nil,
MTLPixelFormat.bgra8Unorm,
width,
height,
0, &texture)
guard result2 == kCVReturnSuccess,
let cvTexture = texture,
let mtlTexture = CVMetalTextureGetTexture(cvTexture) else {
return nil
}
mtlTexture.label = _textureName
let depthBuffer = device.makeBuffer(bytes: depthData, length: depthData.count * MemoryLayout<Float>.stride)!
return (mtlTexture, depthBuffer)
}
}
Above's my code - could someone point out what might be wrong?
I ran into a memory issue that I don't understand why this could happen. For me, It seems like ARC doesn't guarantee thread-safety.
Let see the code below
@propertyWrapper
public struct AtomicCollection<T> {
private var value: [T]
private var lock = NSLock()
public var wrappedValue: [T] {
set {
lock.lock()
defer { lock.unlock() }
value = newValue
}
get {
lock.lock()
defer { lock.unlock() }
return value
}
}
public init(wrappedValue: [T]) {
self.value = wrappedValue
}
}
final class CollectionTest: XCTestCase {
func testExample() throws {
let rounds = 10000
let exp = expectation(description: "test")
exp.expectedFulfillmentCount = rounds
@AtomicCollection var array: [Int] = []
for i in 0..<rounds {
DispatchQueue.global().async {
array.append(i)
exp.fulfill()
}
}
wait(for: [exp])
}
}
It will crash for various reasons (see screenshots below)
I know that the test doesn't reflect typical application usage. My app is quite different from traditional app so the code above is just the simplest form for proof of the issue.
One more thing to mention here is that array.count won't be equal to 10,000 as expected (probably because of copy-on-write snapshot)
So my questions are
Is this a bug/undefined behavior/expected behavior of Swift/Obj-c ARC?
Why this could happen?
Any solutions suggest?
How do you usually deal with thread-safe collection (array, dict, set)?
`
init() {
nextOrder = self.AllItems.map{$0.order}.max()
if nextOrder == nil {
nextOrder = 0
}
nextOrder! += 1 // <--- Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
}
`
I have to say, Swift is great - when it works!
Hello all.
This is my code snippet.
RecordListView()
.tabItem {
Label("Record List", systemImage: "list.clipboard")
}
.tag(Tab.RecordList)
When I export localizations, there is no Record List in the .xcloc file.
Then I use LocalizedStringKey for Label and export localizations file, the code is as follows:
let RecordsString:LocalizedStringKey = "Tab.Records"
RecordListView()
.tabItem {
Label(RecordsString, systemImage: "list.clipboard")
}
.tag(Tab.RecordList)
There is still no Tab.Records.
Hi,
I have a complex structure of classes, and I'm trying to migrate to swift6
For this classes I've a facade that creates the classes for me without disclosing their internals, only conforming to a known protocol
I think I've hit a hard wall in my knowledge of how the actors can exchange data between themselves. I've created a small piece of code that can trigger the error I've hit
import SwiftUI
import Observation
@globalActor
actor MyActor {
static let shared: some Actor = MyActor()
init() {
}
}
@MyActor
protocol ProtocolMyActor {
var value: String { get }
func set(value: String)
}
@MyActor
func make(value: String) -> ProtocolMyActor {
return ImplementationMyActor(value: value)
}
class ImplementationMyActor: ProtocolMyActor {
private(set) var value: String
init(value: String) {
self.value = value
}
func set(value: String) {
self.value = value
}
}
@MainActor
@Observable
class ViewObserver {
let implementation: ProtocolMyActor
var value: String
init() async {
let implementation = await make(value: "Ciao")
self.implementation = implementation
self.value = await implementation.value
}
func set(value: String) {
Task {
await implementation.set(value: value)
self.value = value
}
}
}
struct MyObservedView: View {
@State var model: ViewObserver?
var body: some View {
if let model {
Button("Loaded \(model.value)") {
model.set(value: ["A", "B", "C"].randomElement()!)
}
} else {
Text("Loading")
.task {
self.model = await ViewObserver()
}
}
}
}
The error
Non-sendable type 'any ProtocolMyActor' passed in implicitly asynchronous call to global actor 'MyActor'-isolated property 'value' cannot cross actor boundary
Occurs in the init on the line "self.value = await implementation.value"
I don't know which concurrency error happens... Yes the init is in the MainActor , but the ProtocolMyActor data can only be accessed in a MyActor queue, so no data races can happen... and each access in my ImplementationMyActor uses await, so I'm not reading or writing the object from a different actor, I just pass sendable values as parameter to a function of the object..
can anybody help me understand better this piece of concurrency problem?
Thanks
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.0, 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
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
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
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
notes: This loosen strict concurrency checking in a number of subtle ways.
SE-0442 Allow TaskGroup's ChildTaskResult Type To Be Inferred
link: SE-0442
notes: This represents a small quality of life improvement for withTaskGroup(…) and withThrowingTaskGroup(…).
In Progress
The proposals in this section didn’t make Swift 6.0.
SE-0371 Isolated synchronous deinit
link: SE-0371
availability: Swift 6.1
introduces: isolated deinit
notes: Allows a deinitialiser to access non-sendable isolated state, lifting a restriction imposed by SE-0327.
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 it’s not clear whether it’ll come back in anything resembling this guise.
SE-0449 Allow nonisolated to prevent global actor inference
link: SE-0449
availability: Swift 6.1
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.
import Foundation
import FirebaseAuth
import GoogleSignIn
import FBSDKLoginKit
class AuthController {
// Assuming these variables exist in your class
var showCustomAlertLoading = false
var signUpResultText = ""
var isSignUpSucces = false
var navigateHome = false
// Google Sign-In
func googleSign() {
guard let presentingVC = (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.windows.first?.rootViewController else {
print("No root view controller found.")
return
}
GIDSignIn.sharedInstance.signIn(withPresenting: presentingVC) { authentication, error in
if let error = error {
print("Error: \(error.localizedDescription)")
return
}
guard let authentication = authentication else {
print("Authentication is nil")
return
}
guard let idToken = authentication.idToken else {
print("ID Token is missing")
return
}
guard let accessToken = authentication.accessToken else {
print("Access Token is missing")
return
}
let credential = GoogleAuthProvider.credential(withIDToken: idToken.tokenString, accessToken: accessToken.tokenString)
self.showCustomAlertLoading = true
Auth.auth().signIn(with: credential) { authResult, error in
guard let user = authResult?.user, error == nil else {
self.signUpResultText = error?.localizedDescription ?? "Error occurred"
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.showCustomAlertLoading = false
}
return
}
self.signUpResultText = "\(user.email ?? "No email")\nSigned in successfully"
self.isSignUpSucces = true
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
self.showCustomAlertLoading = false
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.navigateHome = true
}
}
print("\(user.email ?? "No email") signed in successfully")
}
}
}
// Facebook Sign-In
func signInWithFacebook(presentingViewController: UIViewController, completion: @escaping (Bool, Error?) -> Void) {
let manager = LoginManager()
manager.logIn(permissions: ["public_profile", "email"], from: presentingViewController) { result, error in
if let error = error {
completion(false, error)
return
}
guard let result = result, !result.isCancelled else {
completion(false, NSError(domain: "Facebook Login Error", code: 400, userInfo: nil))
return
}
if let token = result.token {
let credential = FacebookAuthProvider.credential(withAccessToken: token.tokenString)
Auth.auth().signIn(with: credential) { (authResult, error) in
if let error = error {
completion(false, error)
return
}
completion(true, nil)
}
}
}
}
// Email Sign-In
func signInWithEmail(email: String, password: String, completion: @escaping (Bool, Error?) -> Void) {
Auth.auth().signIn(withEmail: email, password: password) { (authResult, error) in
if let error = error {
completion(false, error)
return
}
completion(true, nil)
}
}
}
I make some small program to make dots. Many of them.
I have a Generator which generates dots in a loop:
//reprat until all dots in frame
while !newDots.isEmpty {
virginDots = []
for newDot in newDots {
autoreleasepool{
virginDots.append(
contentsOf: newDot.addDots(in: size, allDots: &result, inSomeWay))
}
newDots = virginDots
}
counter += 1
print ("\(result.count) dots in \(counter) grnerations")
}
Sometimes this loop needs hours/days to finish (depend of inSomeWay settings), so it would be very nice to send partial result to a View, and/or if result is not satisfying — break this loop and start over.
My understanding of Tasks and Concurrency became worse each time I try to understand it, maybe it's my age, maybe language barier. For now, Button with {Task {...}} action doesn't removed Rainbow Wheel from my screen. Killing an app is wrong because killing is wrong.
How to deal with it?
In below Swift code , is there any possiblities of failure of Unmanaged.passRetain and Unmanaged.takeRetain calls ?
// can below call fail (constructor returns nil due to OS or language error) and do i need to do explicit error handling here?
let str = TWSwiftString(pnew)
// Increasing RC by 1
// can below call fail (assuming str is valid) and do i need to do explicit error handling for the same ?
let ptr:UnsafeMutableRawPointer? = Unmanaged.passRetained(str).toOpaque()
// decrease RC by 1
// can below call fail (assuming ptr is valid) ? and do i need to do explicit error handling
Unmanaged<TWSwiftString>.fromOpaque(pStringptr).release()
I'm using this library for encoding / decoding RSA keys. https://github.com/Kitura/BlueRSA
It's worked fine up until macOS sequoia. The issue I'm having is the tests pass when in Debug mode, but the moment I switch to Release mode, the library no longer works.
I ruled this down the swift optimization level.
If I change the Release mode to no optimization, the library works again. Wondering where in the code this could be an issue? How would optimization break the functionality?
Hi all,
Background:
I am working as a library developer and would like to enable Swift C++ interoperability in our library. Our library supports both CocoaPods and SPM.
Question:
I would like to know whether it is possible to avoid breaking changes bring to the library users after enabling Swift C++ interoperability.
In my experiment, all apps and packages depend on the library needs to enable interoperability in Xcode or package manage tools, otherwise the source code cannot be complied.
I am wondering is there any ways to bypass this? For example, is there a way to only enable Swift C++ interoperability only in our libraries?
macOS: Sequoia
Xcode: 16.1
I am working on a macOS app and it has a widget feature.
When I use Swift 6 (Build Settings > Swift Language Version) in IntentExtension, the intent configuration won't show up in macOS Sequoia.
If I downgrade to Swift 5, it works without any other changes.
Is it a bug or am I missing something? How can I use Swift 6 with IntentExtension.
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'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,
}
Crash stack last 2 lines are- libswiftCore.dylib swift_unknownObjectRetain libswiftCore.dylib String._bridgeToObjectiveCImpl()
String._bridgeToObjectiveCImpl() gets called when the caller and implementation is in Swift file
I believe due to @objc class LauncherContainer there'd be bridging header generated. Does that mean tabId passed to tabContentCellItemDidTap is a String but the one passed to initiateNewTabNavigation is NSString?
TabId is UUID().uuidString if that helps. Wondering if UUID().uuidString has something to do with this.
Thanks a ton for helping. Please find attached screenshot of the stack trace.
In my project, i have a Swift class with a class level property of type string. Like this :
class TWSwiftString {
var pString:String!
init(_ pString: String) {
self.pString = pString
}
}
I am creating intance of this class and then creating a opaque pointer to this intance. Like this :
let str = TWSwiftString("World")
// Increasing RC by 1
strptr = Unmanaged.passRetained(str).toOpaque()
Now using this opaque pointer i want to modify the value of pString by directly operating on memory. Like this:
withUnsafeMutablePointer(to: &strptr.pString) { strPointer in
strPointer.pointee = "World"
}
Although i am able to modify pString like this and print. Lets assume i have a approach to make sure memory remains valid when it is operated on and freeing of memory is also handled somehow .
Will this approach work if i have 100s of intance of this string which are being operated in this manner ? What if the size of new value is greater than existing string value ? For this i am thinking of chunk of memory initially and then keep on increasing size of it as bigger string then this chunk comes. Does this approach seems feasible ? Any other problems i can encounter by using this approach ?
Chatgpt gave this answer :
To directly update the memory of a Swift class’s property, particularly to alter a String property, is generally discouraged due to Swift's memory safety model. However, if we want to access and modify a class property directly, the best practice is to use a property accessor, as manually altering memory could lead to undefined behavior or even crashes. Why Direct Memory Manipulation Is Risky When you attempt to manipulate memory directly, especially with Swift’s memory model, you might alter not only the value but also the memory layout of Swift’s String type, which could break things internally. The Swift compiler may store String differently based on the internal structure, so even if we manage to locate the correct memory address, directly modifying it is unreliable.
do you have any opinion around chatgpt resoponse ?
I am using swiftui lately in my iOS mobile app, The Mobile app already has a pipeline that detect any experimental features and throw an error
I am using swift 5 and as you all know SwiftUI is using some of OpaqueTypeErasure utility types like "some"
I heard that in swift 6 the OpaqueTypeErasure is not experimental anymore
But upgrading the app swift version will be a very long process
Also changing the pipeline will be a very long and tiring process
So i want to know if there is a way to remove OpaqueTypeErasure from SwiftUI and what is the alternatives for bypassing the error that being thrown from the pipeline
I used struct in the swift file, but once I use xcode build. It will automatically change to enum, causing build failure. But it turns out that this file can be used to build. Since upgrading to XCode16.1, it's not working anymore. I don't know where to set it up. Do not optimize or modify my code.
Error message: 'Padding' cannot be constructed because it has no accessible initializers
My environment is:
macos sequoia 15.1
xcode 16.1(16B40)
File source code:
let π: CGFloat = .pi
let customUserAgent: String = "litewallet-ios"
let swiftUICellPadding = 12.0
let bigButtonCornerRadius = 15.0
enum FoundationSupport {
static let dashboard = "https://support.litewallet.io/"
}
enum APIServer {
static let baseUrl = "https://api-prod.lite-wallet.org/"
}
enum Padding {
subscript(multiplier: Int) -> CGFloat {
return CGFloat(multiplier) * 8.0
}
subscript(multiplier: Double) -> CGFloat {
return CGFloat(multiplier) * 8.0
}
}
enum C {
static let padding = Padding()
enum Sizes {
static let buttonHeight: CGFloat = 48.0
static let sendButtonHeight: CGFloat = 165.0
static let headerHeight: CGFloat = 48.0
static let largeHeaderHeight: CGFloat = 220.0
}
static var defaultTintColor: UIColor = UIView().tintColor
Enum was originally SRTUCT. But the build has been automatically optimized
I would like to see examples of how to do this. Apple states that explicit clang modules don't work with C++ interop. ObjC++ has simple interop with C++. Swift does not. And so I'd like to know how to setup my C++ projects to build them as clang modules.