Discuss Swift.

Swift Documentation

Post

Replies

Boosts

Views

Activity

Returning Typed Pointer From Swift to C++
I have a struct defined in Swift, i want to pass it's instance pointer from swift to C++. When I am trying to directly return Typed Pointer from Swift Function to C++, the function doesn't get expose to C++. Code which i have tried. // Defined Structure public struct MyStruct { public init (_ pValue : Int) { uValue = pValue } public var uValue : Int } var my_struct = MyStruct(20) // Function which returns Struct Pointer to C++ // When I return typed pointer this function doesn't get exposed to C++ public func PassStructPointer () -> UnsafeMutablePointer<MyStruct> { withUnsafeMutablePointer(to: &my_struct) { pointer in return pointer } } But when I pass UnsafeRawMutablePointer instead of type pointer then the function does get expose to C++ var my_struct = MyStruct(20) // This get expose to C++. public func PassStructPointer () -> UnsafeMutableRawPointer { return withUnsafeMutableBytes(of: &my_struct) { pointer in return pointer.baseAddress! } } Can we not pass typed pointer of the types defined by us?
2
0
172
2w
UnsafeMutablePointer direct exposure.
I am trying to use the swift type UnsafeMutablePointer directly in C++. According to the documentation mentioned, swift expose this type to C++. But I am not able to use it . void GetPointerFromSwift () { // Calls a swift function to get a pointer. swift::UnsafeMutablePointer<swit::Int> x = Interop::GetPointer () }
7
0
241
2w
Local push, sending custom data like APN
Hello, I'm doing some test and I dowload the sample from here https://developer.apple.com/documentation/networkextension/local_push_connectivity/receiving_voice_and_text_communications_on_a_local_network Everything works correctly and the phones are able to exchange messages without problems and the server sends pushes to the devices. Now I would like to modify the server so that, when it sends the push to the mobile device, it can change the sound or add other information as is possible when using APN. Now I would like to modify the server so that, when it sends the push to the mobile device, it can change the sound or add other information as is possible when using APN. Is there any way to send a payload like for APN? Thank's Omar
1
0
175
2w
Python vs Swift for macOS CLI tool?
We have an in-house CLI tool built entirely in Python to help us with OS-level workflows. It’s been excellent, but we’re encountering some growing pains. We’ve encountered a case where we’d like to use Apple’s Authorization Plugin, which we can’t directly utilize in Python. Since I doubt this’ll be the last time we encounter Swift or Obj-C specific tools, I’m starting to wonder if a total rewrite into Swift might be in order. Alternatives include writing a wrapper in Swift just for the Auth Plugin, exposing an API that we’ll consume in Python. Since this will only ever be a macOS, tool, I’m starting to feel like going with Python was a dumb idea in the first place. Would love to know what you guys think. p.s. I was advised to post my question on these forums in hopes of being graced by the Apple god Quinn, “The Eskimo”.
2
0
246
3w
Validity of Pointer Returned by withUnsafePointer During CPU Time Slicing
Hello, I am using the withUnsafePointer API in Swift and have a question regarding the validity of the pointer returned by this API. Specifically, I want to understand if the pointer remains valid if the CPU performs a context switch due to its time-slicing mechanism while the closure is executing. Is the pointer returned by withUnsafePointer guaranteed to be valid throughout the entire execution of the closure, even if a CPU context switch occurs as part of time slicing?
2
0
318
4w
Performance with large @Published struct
I'm looking at performance around large codable nested structures that come in from HTTP/JSON. We are seeing stalls on the main thread, and after reviewing all the code, the webrequests and parsing are async and background. The post to set the new struct value (80K) is handled on mainthread. When I looked at the nested structures, they are about 80K. Reading several articles and posts suggested that observing structs will cause a refresh on any change. And that large structures will take longer as they have to be copied for passing to each observer. And that more observers will slow things down. So a made a test app to verify these premises. The app has an timer animating a slider. A VM with a structure containing a byte array. Sliders to scale the size of the byte array from 10K to 200K and to scale the number of observers from 1 to 100. It also measures the actual duration between the timer ticks. My intention is to be able to visual see mainthread stalls and be able to measure them and see the average and max frame delays. Using this to test I found little difference in performance given different structure sizes or number of observers. I'm not certain if this is expected or if I missing something in creating my test app. I have also created a variation where the top struct is a an observable class. I see no difference between struct or class. I'm wondering if this is due to copy-on-mutate causing the struct to actually be passed as reference under the good? I wonder if other optimizations are minimizing the affect of scaling from 1 to 100 observers. I appreciate any insights & critiques. #if CLASS_BASED class LargeStruct: ObservableObject { @Published var data: [UInt8] init(size: Int = 80_000) { self.data = [UInt8](repeating: 0, count: size) } func regenerate(size: Int) { self.data = [UInt8](repeating: UInt8.random(in: 0...255), count: size) } var hashValue: String { let hash = SHA256.hash(data: Data(data)) return hash.compactMap { String(format: "%02x", $0) }.joined() } } #else struct LargeStruct { var data: [UInt8] init(size: Int = 80_000) { self.data = [UInt8](repeating: 0, count: size) } mutating func regenerate(size: Int) { self.data = [UInt8](repeating: UInt8.random(in: 0...255), count: size) } var hashValue: String { let hash = SHA256.hash(data: Data(data)) return hash.compactMap { String(format: "%02x", $0) }.joined() } } #endif class ViewModel: ObservableObject { @Published var largeStruct = LargeStruct() } struct ContentView: View { @StateObject var vm = ViewModel() @State private var isRotating = false @State private var counter = 0.0 @State private var size: Double = 80_000 @State private var observerCount: Double = 10 // Variables to track time intervals @State private var lastTickTime: Date? @State private var minInterval: Double = .infinity @State private var maxInterval: Double = 0 @State private var totalInterval: Double = 0 @State private var tickCount: Int = 0 var body: some View { VStack { Model3D(named: "Scene", bundle: realityKitContentBundle) .padding(.bottom, 50) // A rotating square to visualize stalling Rectangle() .fill(Color.blue) .frame(width: 50, height: 50) .rotationEffect(isRotating ? .degrees(360) : .degrees(0)) .animation(.linear(duration: 2).repeatForever(autoreverses: false), value: isRotating) .onAppear { isRotating = true } Slider(value: $counter, in: 0...100) .padding() .onAppear { Timer.scheduledTimer(withTimeInterval: 0.005, repeats: true) { timer in let now = Date() if let lastTime = lastTickTime { let interval = now.timeIntervalSince(lastTime) minInterval = min(minInterval, interval) maxInterval = max(maxInterval, interval) totalInterval += interval tickCount += 1 } lastTickTime = now counter += 0.2 if counter > 100 { counter = 0 } } } HStack { Text(String(format: "Min: %.3f ms", minInterval * 1000)) Text(String(format: "Max: %.3f ms", maxInterval * 1000)) Text(String(format: "Avg: %.3f ms", (totalInterval / Double(tickCount)) * 1000)) } .padding() Text("Hash: \(vm.largeStruct.hashValue)") .padding() Text("Hello, world!") Button("Regenerate") { vm.largeStruct.regenerate(size: Int(size)) // Trigger the regeneration with the selected size } Button("Clear Stats") { minInterval = .infinity maxInterval = 0 totalInterval = 0 tickCount = 0 lastTickTime = nil } .padding(.bottom) Text("Size: \(Int(size)) bytes") Slider(value: $size, in: 10_000...200_000, step: 10_000) .padding() Text("Number of Observers: \(observerCount)") Slider(value: $observerCount, in: 1...100, step: 5) .padding() HStack { ForEach(0..<Int(observerCount), id: \.self) { index in Text("Observer \(index + 1): \(vm.largeStruct.data[index])") .padding(5) } } } .padding() } }
5
0
301
4w
New open-source package, RJSwiftMacros!
🚀 I am thrilled to announce my latest open-source project, RJSwiftMacros! This Swift package enables developers to enhance efficiency by simplifying code generation and automating repetitive tasks in their projects. 🔥 Here's a glimpse of what you can accomplish with RJSwiftMacros: Generate mock data using @MockBuilder macro. Generate coding keys using @CodingKeys macro. RJSwiftMacros is actively maintained and welcomes contributions! 🤝 🔗 GitHub Repository: https://lnkd.in/dPikQTjD I look forward to your feedback and ideas to further enhance its value for the Swift community. 💻
1
0
238
3w
Understanding how ARC is different for Struct vs Class
Hi, I was trying to understand how swift manages it memory just wanted to verify my understanding on it. For Value Types i.e. Struct ARC (Automatic Reference Counting) is not there, Memory is Managed/Confined on the basis of scope of that Variable. And For Struct whenver we do assignment a Copy is been created. For Classes, Swift Manages Memroy with the help of ARC i.e. whenever I create a instance of class its reference count get increased and when we assign same instance to new variable then it also result in increment of Reference Count. The Memory will get deallocated when all the variables pointing to that object are no longer in use.
1
0
250
4w
How to pass Child Class reference as Parent Class
So I have this child class with a function that creates a perdetermined array of other classes. class DirectGame : GameParent { static func GetAllChallenges() -> Array<ChallengeParent>{ return [LockdownChallenge(game: self)] } } These other classes take in a GameParent class in the initalizer like so: class LockdownChallenge { var game : GameParent init(game: GameParent) { self.game = game } } However this line return [LockdownChallenge(game: self)] is throwing the error "Cannot convert value of type 'DirectGame.Type' to expected argument type 'GameParent'" How do I pass in a reference to DirectGame into the initalizer of ChallengeParent?
2
0
258
Aug ’24
How ARC works withUnsafeMutablePointer Interface.
I am using withUnsafeMutablePointer to get raw pointer from Data. Once I get a Pointer I follow these steps: I create a Wrapper using that Pointer. After that I increase it ARC and pass it as a opaque to C++ When I was on First Step if my thread get suspended and after some time if it resumes then is there a possibility that the Memory will get freed due to ARC. Adding basic Code Flow depicting what i am doing. public class DataHolder { public init () {} public var data_wrapper : Data? } func InternalReceiveHandler (_ pContent : Data?) -> Void { var holder : DataHolder = DataHolder.init () withUnsafeMutablePointer (to : &pContent) { data_pointer in holder.data_wrapper = Data.init (noBytesCopy : data_pointer, count : no_of_bytes, deallocator : .none) return Unmanaged.passRetained (holder).toOpaque () } } Is there a possibility that when I am creating the wrapper my thread get suspended and when it get resumed the Memory the pointer was pointing can be freed by ARC.
5
0
346
Aug ’24
NIOThreadPool segfault
Following the latest Command Line Tools update, the swift-nio library (https://github.com/apple/swift-nio) causes my program to segfault. The function where the error occurs is runIfActive, which is executed with the following error: Thread 12: EXC_BAD_ACCESS (code=1, address=0x4) swift version: swiftlang-6.0.0.7.6 clang-1600.0.24.1 NIO version: 2.70.0
1
0
189
Aug ’24
Await expectations with Swift Testing?
I'm used to wait for expectations when using XCTest, but I'm completely stumped by the seemingly-absent option for expecting some parts of my code to be called in Swift Testing 🤔 Consider the following: protocol MyAPI { func getData() async throws -> String } class MockAPI: MyAPI { let stub: () async throws -> String init(stub: @escaping () async throws -> String = { "hello" }) { self.stub = stub } func getData() async throws -> String { try await stub() } } Which is being used in my view model: class MyViewModel: ObservableObject { private let api: MyAPI @Published var data: String init(api: MyAPI) { self.api = api } func refresh() async throws { self.data = try await api.getData() } } When I wrote tests in the past, I would simply override the stub of the MockAPI implementation and fulfill an expectation in there: class MyViewModelTests: XCTestCase { func testModelCallsAPIOnRefresh() async throws { let expectCallsAPI = expectation("Model should call API") let api = MockAPI { expectCallsAPI.fulfill() return "hello" } let model = MyViewModel(api: api) try await model.refresh() await fulfillment(of: [expectCallsAPI], timeout: 1) } } How would I go about checking that my model does indeed call the API when using Swift Testing?
1
0
239
Aug ’24
Task not executing at all
I have an 8th generation iPad, now updated with iPadOS 16.2 (20C65) and I have an issue that I also saw on earlier 16.* betas. Task is not executing at all. This is so frustrating because I have adopted async/await in my app, I support iOS 15+, everything was working fine but now that stuff inside Task { } is not executed my app seems to be broken. (Note: my main device is an iPhone 11, still on iOS 16.0, and it works fine there.) It is also frustrating to see no other developers are complaining about this, like it happens only with my app. I have debugged with print statements and breakpoints and I can say for sure that stuff is not executing. Does anybody have any ideas? Anything else I can try? FB11866066
17
0
3.2k
Dec ’22
How to prevent screen recording from iOS 18 onwards as isCaptured is deprecated from iOS 18 ?
I am developing an iPhone app related to finance and currently I am using isCaptured value to prevent screen recording by checking the isCaptured value and if it is true then I blur the video recording. It was working fine while using UIScreen.main.isCaptured till iOS 17 . But for iOS 18 it became deprecated and it is not working any more. Below is the obj-c code block. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions { if (@available(iOS 11.0, *)) { BOOL isCaptured = [[UIScreen mainScreen] isCaptured]; if(isCaptured){ // Do the action for hiding the screen recording } } else{ // Fallback on earlier versions } return YES; } The replacement sceneCaptureState is working only for a scene-based app which uses UISceneDelegate lifecycle but it's not working for the old structure so now i have that problem, my iPhone app is very big and does not support scenes at all since we are following UIAppDelegate life cycle for years, what shall I do to prevent screen recording from iOS 18 onwards ? Note: My iPhone app does not support any scene configuration Please help me in this. Regards, Carol
2
1
372
Aug ’24