Dive into the world of programming languages used for app development.

All subtopics
Posts under Programming Languages topic

Post

Replies

Boosts

Views

Activity

Logo flying from the corner
Whenever I load a resized image into a 70 by 70 frame, when I run the loading screen on the simulator, it looks like the image is flying from the top left corner of the screen on load, however, when I load it in the previews, it starts where its supposed to be in the center. Both are scaled properly, however, the first ones position is acting like I put a transition on it when I did not import SwiftUI struct LoadingView: View { @Environment(\.colorScheme) private var colorScheme var text: String? = nil @State private var isSpinning = false var body: some View { VStack{ Image("Jeromes_Logo") .resizable() .frame(width: 70, height: 70) .rotationEffect(.degrees(isSpinning ? 360 : 0)) .animation( .bouncy(duration: 0.4, extraBounce: 0.2) .repeatForever(autoreverses: false), value: isSpinning ) .onAppear { isSpinning = true } if let text = text { Text(text) } } .frame(maxWidth: .infinity, maxHeight: .infinity) } } #Preview { LoadingView(text: "loading") }
2
0
185
1d
AsyncStream does not cancel inner Task
AsyncStream { continuation in Task { let response = await getResponse() continuation.yield(response) continuation.finish() } } In this WWDC video https://developer.apple.com/videos/play/wwdc2025/231/ at 8:20 the presenter mentions that if the "Task gets cancelled, the Task inside the function will automatically get cancelled too". The documentation does not mention anything like this. From my own testing on iOS 18.5, this is not true.
2
0
259
2d
Passing string between Swift and C++
I want to understand what the recommended way is for string interoperability between swift and c++. Below are the 3 ways to achieve it. Approach 2 is not allowed at work due to restrictions with using std libraries. Approach 1: In C++: char arr[] = "C++ String"; void * cppstring = arr; std::cout<<"before:"<<(char*)cppstring<<std::endl;           // C++ String // calling swift function and passing the void buffer to it, so that swift can update the buffer content Module1::SwiftClass:: ReceiveString (cppstring, length);   std::cout<<"after:"<<(char*)cppstring<<std::endl;             // SwiftStr      In Swift: func ReceiveString (pBuffer : UnsafeMutableRawPointer , pSize : UInt ) -> Void { // to convert cpp-str to swift-str: let swiftStr = String (cString: pBuffer.assumingMemoryBound(to: Int8.self)); print("pBuffer content: \(bufferAsString)"); // to modify cpp-str without converting: let swiftstr:String = "SwiftStr"      _ =  swiftstr.withCString { (cString: UnsafePointer<Int8>) in pBuffer.initializeMemory(as: Int8.self, from: cString, count: swiftstr.count+1) } }  Approach 2:  The ‘String’ type returned from a swift function is received as ‘swift::String’ type in cpp. This is implicitly casted to std::string type. The std::string has the method available to convert it to char *. void TWCppClass::StringConversion () {     // GetSwiftString() is a swift call that returns swift::String which can be received in std::string type     std::string stdstr = Module1::SwiftClass::GetSwiftString ();     char * cstr = stdstr.data ();     const char * conststr= stdstr.c_str (); }    Approach 3: The swift::String type that is obtained from a swift function can be received in char * by directly casting the address of the swift::String. We cannot directly receive a swift::String into a char *. void TWCppClass::StringConversion () {    // GetSwiftString() is a swift call that returns swift::String    swift::String swiftstr = Module1::SwiftClass::GetSwiftString ();    // obtaining the address of swift string and casting it into char *    char * cstr = (char*)&swiftstr; }
1
0
302
3d
Load bundle resources in UI Tests
I want to load images from my bundle, which works fine when running the main app. However this does not work when running UI Tests. I read that the test bundle is not the main bundle when running tests. I try loading the bundle via this snippet: let bundle = Bundle(for: Frames_HoerspielUITests.self) This is my test class wrapped these the canImport statements so it can be added to the main app target and used for getting the correct bundle: #if canImport(XCTest) import XCTest final class Frames_HoerspielUITests: XCTestCase { override func setUpWithError() throws { continueAfterFailure = false } override func tearDownWithError() throws { } @MainActor func testExample() throws { let app = XCUIApplication() app.launch() } @MainActor func testLaunchPerformance() throws { measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } #else final class Frames_HoerspielUITests { } #endif However while this works when running the main app, it still fails in the UI tests. It is a SwiftUI only app. and I can't add the images to the asset catalog because they are referenced from another location. Any ideas? Thank you
1
0
203
3d
Range For Keys and Values Of Dictionary
I came across a code let myFruitBasket = ["apple":"red", "banana": "yellow", "budbeeri": "dark voilet", "chikoo": "brown"] Can we have range for keys and values of dictionary, it will be convenient for keys print(myFruitBasket.keys[1...3]) // banana, budbeeri, chikoo same for values print(myFruitsBasket.values[1...3]) // yellow, voilet, brown
1
0
375
1w
Modifying an associated value of an existing enum instance
Hi, I would like to modify an associated value of an existing enum instance of the the following enum: enum FilterItem: Equatable, Hashable { case work(isSelected: Bool) ... var filterName: String { switch self { case .work: return "Work" ... } } var isSelected: Bool { switch self { case .work(let isSelected): return isSelected ... } } I want to be able to switch on the FilterItem type and then to be able to modify the isSelected property of the instance like: let itemToChange: FilterItem switch item { case .work(let isSelected): itemToChange.isSelected = !isSelected I know the above code doesn't compile, but I was wondering if there was a way I could modify my enum instance without creating a totally new enum instance.
5
0
339
1w
Swapping the `objectAtIndex:` method of `__NSArrayM` using `method_exchangeImplementations` will lead to continuous memory growth.
After swapping the -objectAtIndex: method using method_exchangeImplementations, it will cause continuous memory growth. Connect the iPhone and run the provided project. Continuously tap the iPhone screen. Observe Memory; it will keep growing. Sample code
2
0
282
1w
Swift OpenAPI Generator Error
PLATFORM AND VERSION iOS Development environment: Xcode 26, macOS 26 Run-time configuration: iOS 18 and up DESCRIPTION OF PROBLEM I am on the beta version of os 26 for both Xcode and macOS. When I try to run my project, which has the Swift OpenAPI Generator from apple, it gives the error "unsupported configuration: the aggregate target 'OpenAPIGenerator' has package dependencies, but targets that build for different platforms depend on it" STEPS TO REPRODUCE Install macOS 26 and Xcode 26 and try running an iOS app built for iOS 18.0 and up wit the OpenAPIGenerator package on a physical iPhone running iOS 26
1
0
317
1w
Tuple Comparision
I was trying to evaulate let myTuple = ("blue", false) let otherTuple = ("blue", true) if myTuple &lt; otherTuple { print("yes it evaluates") } Ans I got /tmp/S9jAk7P7KW/main.swift:5:12: error: binary operator '&lt;' cannot be applied to two '(String, Bool)' operands if myTuple &lt; otherTuple { My question is why there is no compile time issue in first place where the declaration is let myTuple = ("blue", false) ~~~~~~ something like above
2
0
423
2w
Swift/C++ interoperability issue in std::string
In scope of one of our project we've faced an issue with constant crashes when integrating C++ library in Swift code using Swift/C++ interoperability. Investigating the root causes of the issue we've discovered that with new version of Swift bug was introduced. Long story short: for strings bigger than 27 symbols memory is feed incorrectly that causes the crashes. By creating this post I wanted to draw community's attention to the problem and promote it to be solved quicker as for now it is not addressed.
1
0
485
2w
Exposing Objective-C API to Swift inside a Framework (Private Framework API)
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?
0
0
227
2w
Crash in libswiftCore with swift::RefCounts
I'm seeing somewhat regular crash reports from my app which appear to be deep in the Swift libraries. They're happening in the same spot, so I'm apt to believe something is likely getting deallocated behind the scenes - but I don't really know how to guard against it. Here's the specific crash thread: 0 libsystem_kernel.dylib 0x00000001d51261dc __pthread_kill + 8 (:-1) 1 libsystem_pthread.dylib 0x000000020eaa8b40 pthread_kill + 268 (pthread.c:1721) 2 libsystem_c.dylib 0x000000018c5592d0 abort + 124 (abort.c:122) 3 libsystem_malloc.dylib 0x0000000194d14cfc malloc_vreport + 892 (malloc_printf.c:251) 4 libsystem_malloc.dylib 0x0000000194d14974 malloc_report + 64 (malloc_printf.c:290) 5 libsystem_malloc.dylib 0x0000000194d0e8b4 ___BUG_IN_CLIENT_OF_LIBMALLOC_POINTER_BEING_FREED_WAS_NOT_ALLOCATED + 32 (malloc_common.c:227) 6 Foundation 0x0000000183229f40 __DataStorage.__deallocating_deinit + 104 (Data.swift:563) 7 libswiftCore.dylib 0x0000000182f556c8 _swift_release_dealloc + 56 (HeapObject.cpp:847) 8 libswiftCore.dylib 0x0000000182f5663c bool swift::RefCounts&lt;swift::RefCountBitsT&lt;(swift::RefCountInlinedness)1&gt;&gt;::doDecrementSlow&lt;(swift::PerformDeinit)1&gt;(swift::RefCountBitsT&lt;(swift::RefCountInlinedness)1&gt;, unsigned int) + 152 (RefCount.h:1052) 9 TAKAware 0x000000010240c688 StreamParser.parseXml(dataStream:) + 1028 (StreamParser.swift:0) 10 TAKAware 0x000000010240cdb4 StreamParser.processXml(dataStream:forceArchive:) + 16 (StreamParser.swift:85) 11 TAKAware 0x000000010240cdb4 StreamParser.parseCoTStream(dataStream:forceArchive:) + 360 (StreamParser.swift:108) 12 TAKAware 0x000000010230ac3c closure #1 in UDPMessage.connect() + 252 (UDPMessage.swift:68) 13 Network 0x000000018506b68c closure #1 in NWConnectionGroup.setReceiveHandler(maximumMessageSize:rejectOversizedMessages:handler:) + 200 (NWConnectionGroup.swift:458) 14 Network 0x000000018506b720 thunk for @escaping @callee_guaranteed (@guaranteed OS_dispatch_data?, @guaranteed OS_nw_content_context, @unowned Bool) -&gt; () + 92 (&lt;compiler-generated&gt;:0) 15 Network 0x0000000185185df8 invocation function for block in nw_connection_group_handle_incoming_packet(NWConcrete_nw_connection_group*, NSObject&lt;OS_nw_endpoint&gt;*, NSObject&lt;OS_nw_endpoint&gt;*, NSObject&lt;OS_nw_interface&gt;*, NSObje... + 112 (connection_group.cpp:1075) 16 libdispatch.dylib 0x000000018c4ad2b8 _dispatch_block_async_invoke2 + 148 (queue.c:574) 17 libdispatch.dylib 0x000000018c4b7584 _dispatch_client_callout + 16 (client_callout.mm:85) 18 libdispatch.dylib 0x000000018c4d325c _dispatch_queue_override_invoke.cold.3 + 32 (queue.c:5106) 19 libdispatch.dylib 0x000000018c4a21f8 _dispatch_queue_override_invoke + 848 (queue.c:5106) 20 libdispatch.dylib 0x000000018c4afdb0 _dispatch_root_queue_drain + 364 (queue.c:7342) 21 libdispatch.dylib 0x000000018c4b054c _dispatch_worker_thread2 + 156 (queue.c:7410) 22 libsystem_pthread.dylib 0x000000020eaa5624 _pthread_wqthread + 232 (pthread.c:2709) 23 libsystem_pthread.dylib 0x000000020eaa29f8 start_wqthread + 8 (:-1) Basically we're receiving a message via UDP that is an XML packet. We're parsing that packet using what I think it pretty straightforward code that looks like this: func parseXml(dataStream: Data?) -&gt; Array&lt;String&gt; { var events: [String] = [] guard let data = dataStream else { return events } currentDataStream.append(data) var str = String(decoding: currentDataStream, as: UTF8.self) while str.contains(StreamParser.STREAM_DELIMTER) { let splitEvent = str.split(separator: StreamParser.STREAM_DELIMTER, maxSplits: 1) let cotEvent = splitEvent.first! var restOfString = "" if splitEvent.count &gt; 1 { restOfString = String(splitEvent.last!) } events.append("\(cotEvent)\(StreamParser.STREAM_DELIMTER)") str = restOfString } currentDataStream = Data(str.utf8) return events } the intention is that the message may be broken across multiple packets, so we build them up here. Is there anything I can do to guard against these crashes?
5
0
136
2w
Execute Swift scripts dynamically in iOS
I have a transformation function that takes in data, executes some instructions, and returns an output. This function is dynamic and not shipped with the binary. Currently, I’m executing it using JavaScriptCore.JSContext, which works well, but the function itself is written in JavaScript. Is there a way to achieve something similar using Swift – such as executing a dynamic Swift script, either directly or through other means? I know this is possible on macOS, but I’m not sure about iOS. I’ve also heard that extensions might open up some possibilities here. Any insights or alternative approaches would be appreciated.
4
0
240
2w
Ambiguous use of 'textField' in Xcode 26
func textField( _ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String ) -&gt; Bool { if let delegate = delegate, let shouldChangeCharactersIn = delegate.textField { return shouldChangeCharactersIn(textField, range, string) } return true } This is from an extension extension TextInput: UITextFieldDelegate, ObservableTextFieldDelegateProtocol { The delegate is already a UITextFieldDelegate, but when you click on the error, it returns 7 instances of: "Found this candidate in module 'UIKit' (UIKit.UITextFieldDelegate.textField)" This doesn't give an error in Xcode 16. Is this an Xcode 26 bug?
0
0
103
3w
Circular Reference Error in Xcode 26
I have my project running perfectly fine on Xcode 16. However, in Xcode 26 it doesn't build due to an error that I do not understand. I have three files that pertain to this error: // FriendListResponse.swift import Foundation struct FriendListResponse: Decodable { var friendships: [Friendship] var collections: [FriendCollection] } // Friendship.swift import Foundation struct Friendship: Decodable { var createdAt: String var friendId: Int var friendUserId: Int // user ID of the friend var friendUsername: String var id: Int var tagNames: [String] } // FriendCollection.swift struct FriendCollection: Decodable { var id: Int var permalink: String var tagNames: [String] var title: String } On the first file, FriendListResponse.swift, I am the simple error message "circular reference." I do not understand how these self-contained structs could create a circular reference. Although I have other data types in my project, none of them are even referenced in these files except for Friendship and FriendCollection. The FriendListResponse is a struct that is created from JSON values that are fetched from an API. This is the function that fetches the JSON: public static func listFriends(username: String) async throws -> [Friendship] { let data = try await sendGETRequest( url: "people/\(username)/friends/list.json" ) print(String(data: data, encoding: .utf8)!) let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let wrapper = try decoder.decode(FriendListResponse.self, from: data) return wrapper.friendships } // Note: the function sendGETRequest is just // a function that I have created that takes a set // of parameters and returns a data object // using the HTTP GET protocol. I don't think // that it is related to this issue. However, if you // think that it is, I can share the code for that. This error has also happened in a few other cases within contained networks of my data structure. I do not know why this error is only appearing once I launch Xcode 26 beta with my project files. I would think that this error also would appear in Xcode 16.4. Any help would be greatly appreciated in my process to compile my project on Xcode 26!
7
0
179
3w