Is there a swift6 manual that will teach me how to code in swift?
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
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
I am trying to use initialize a Decimal type using its generic binary integer exactly initializer but it keeps crashing with a fatal error regardless of the value used:
Code to reproduce the issue:
let binaryInteger = -10
let decimal = Decimal(exactly: binaryInteger) // error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
Is it a known bug?
Why Ternary operator in not called a binary Operator or ternary Operands ?
question ? answer1 : answer2
When it takes 2 operators ?
I’m stuck with repeated production crashes in my SwiftUI app and I can’t make sense of the traces on my own.
The symbolicated reports show the same pattern:
Crash on com.apple.CFNetwork.LoaderQ with EXC_BAD_ACCESS / PAC failure
Always deep in CFNetwork, most often in
URLConnectionLoader::loadWithWhatToDo(NSURLRequest*, _CFCachedURLResponse const*, long, URLConnectionLoader::WhatToDo)
No frames from my code, no sign of AuthManager or tokens.
What I’ve tried:
Enabled Address Sanitizer,
Malloc Scribble,
Guard Malloc,
Zombies.
Set CFNETWORK_DIAGNOSTICS=3 and collected Console logs.
Stress-tested the app (rapid typing, filter switching, background/foreground, poor network with Network Link Conditioner).
Could not reproduce the crash locally.
So far:
Logs show unrelated performance faults (I/O on main thread, CLLocationManager delegate), but no obvious CFNetwork misuse.
My suspicion is a URLSession lifetime or delegate/auth-challenge race, but I can’t confirm because I can’t trigger it.
Since starting this investigation, I also refactored some of my singletons into @State/@ObservedObject dependencies. For example, my app root now wires up AuthManager, BackendService, and AccountManager (where API calls happen using async/await) as @State properties:
@State var authManager: AuthManager
@State var accountManager: AccountManager
@State var backendService: BackendService
init() {
let authManager = AuthManager()
self._authManager = .init(wrappedValue: authManager)
let backendService = BackendService(authManager: authManager)
self._backendService = .init(wrappedValue: backendService)
self._accountManager = .init(wrappedValue: AccountManager(backendService: backendService))
}
I don’t know if this refactor is related to the crash, but I am including it to be complete.
Apologies that I don’t have a minimized sample project — this issue seems app-wide, and all I have are the crash logs.
Request:
Given the crash location (URLConnectionLoader::loadWithWhatToDo), can Apple provide guidance on known scenarios or misuses that can lead to this crash?
Is there a way to get more actionable diagnostics from CFNetwork beyond CFNETWORK_DIAGNOSTICS to pinpoint whether it’s session lifetime, cached response corruption, or auth/redirect?
Can you also confirm whether my dependency setup above could contribute to URLSession or backend lifetime issues?
I can’t reliably reproduce the crash, and without Apple’s insight the stack trace is effectively opaque to me.
Thanks for your time and help. Happy to send multiple symbolicated crash logs at request.
Thanks for any help.
PS. Including 2 of many similar crash logs. Can provide more if needed.
Atlans-2025-07-29-154915_symbolicated (cfloader).txt
Atlans-2025-08-08-124226_symbolicated (cfloader).txt
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?
Everyone knows that dictionaries in swift are unordered collections, there is no problem with that.
I've noticed some behavior that I can't explain and hope someone can help me.
The first variant
We have a very simple code:
struct Test {
let dict = [1: “1”, 2: “2”, 3: “3”, 4: “4”, 5: “5”]
func test() {
for i in dict {
print(i)
}
}
}
If you call test() several times in a row, the output to the console on my computer looks something like this:
(key: 5, value: “5”)
(key: 1, value: “1”)
(key: 2, value: “2”)
(key: 3, value: “3”)
(key: 4, value: “4”)
(key: 2, value: “2”)
(key: 3, value: “3”)
(key: 1, value: “1”)
(key: 4, value: “4”)
(key: 5, value: “5”)
(key: 1, value: “1”)
(key: 3, value: “3”)
(key: 2, value: “2”)
(key: 5, value: “5”)
(key: 4, value: “4”)
At each new for loop we get a random order of elements
It seemed logical to me, because a dictionary is an unordered collection and this is correct behavior.
However
The second variant
the same code on my colleague's computer, but in the console we see something like this:
(key: 2, value: “2”)
(key: 3, value: “3”)
(key: 1, value: “1”)
(key: 4, value: “4”)
(key: 5, value: “5”)
(key: 2, value: “2”)
(key: 3, value: “3”)
(key: 1, value: “1”)
(key: 4, value: “4”)
(key: 5, value: “5”)
(key: 2, value: “2”)
(key: 3, value: “3”)
(key: 1, value: “1”)
(key: 4, value: “4”)
(key: 5, value: “5”)
always, within the same session, we get the same order in print(i)
We didn't use Playground, within which there may be differences, but a real project.
swift version 5+
we tested on Xcode 14+, 15+ (at first I thought it was because the first version had 14 and the second version had 15, but then a third colleague with Xcode 15 had the behavior from the first scenario)
we did a lot of checks, several dozens of times and always got that on one computer random output of items to the console, and in another case disordered only in the first output to the console
Thanks
I am encountering a strange issue. I have a class that manages a selection of generic items T in an Array. It's a work in progress, but I'l try to give a gist of the setup.
class FileManagerItemModel: NSObject, Identifiable, Codable, NSCopying, Transferable, NSItemProviderReading, NSItemProviderWriting {
var id: URL
static func == (lhs: FileManagerItemModel, rhs: FileManagerItemModel) -> Bool {
lhs.fileURL == rhs.fileURL
}
var fileURL: URL {
FileManagerItemModel.normalizedFileURL(type: type,
rootURL: rootURL,
filePath: filePath)
}
init(type: FileManagerItemType, rootURL: URL, fileURL: URL) {
self.type = type
self.rootURL = rootURL
self.filePath = FileManagerItemModel.filePathRelativeToRootURL(fileURL: fileURL, rootURL: rootURL) ?? "[unknown]"
self.id = FileManagerItemModel.normalizedFileURL(type: type,
rootURL: rootURL,
filePath: filePath)
}
}
The class that manages the selection of these FileManagerItemModels is like so:
@Observable
class MultiSelectDragDropCoordinator<T: Hashable>: ObservableObject, CustomDebugStringConvertible {
private(set) var multiSelectedItems: [T] = []
func addToSelection(_ item: T) {
if !multiSelectedItems.contains(where: { $0 == item }) {
multiSelectedItems.append(item)
}
}
...
}
My issue is that the check if !multiSelectedItems.contains(where: { $0 == item }) in func addToSelection fails. The if is always executed, even if multiSelectedItems contains the given item.
Now, my first thought would be to suspect the static func == check. But that check works fine and does what it should do. Equality is defined by the whole fileURL.
So, the if should have worked. And If I put a breakpoint in func addToSelection on the if, and type po multiSelectedItems.contains(where: { $0 == item }) in the debug console, it actually returns true if the item is in multiSelectedItems. And it properly return false if the item is not in multiSelectedItems.
Still, if I then continue stepping through the app after the breakpoint was hit and I confirmed that the contains should return true, the app still goes into the if, and adds a duplicate item.
I tried assigning to a variable, I tried using a function and returning the true/false. Nothing helps.
Does anyone have an idea on why the debugger shows one (the correct and expected) thing but the actual code still does something different?
Topic:
Programming Languages
SubTopic:
Swift
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.
Hi,
After update to Xcode 16 a lot of errors happen, for example:
import Foundation
extension Collection {
func get(at i: Index) -> Element? {
return indices.contains(i) ? self[i] : nil
}
}
Errors:
Cannot find type 'Index' in scope
Cannot find 'indices' in scope
What is wrong?
Thanks.
I'm using Network Framework to transfer files between 2 devices. The "secondary" device sends file requests to the "primary" device, and the primary sends the files back.
When the primary gets the request, it responds like this:
do {
let data = try Data(contentsOf: filePath)
let priSecDataFilePacket = PriSecDataFilePacket(fileName: filename, dataBlob: data)
let jsonData = try JSONEncoder().encode(priSecDataFilePacket)
let message = NWProtocolFramer.Message(priSecMessageType: PriSecMessageType.priToSecDataFile)
let context = NWConnection.ContentContext(identifier: "TransferUtility", metadata: [message])
connection.send(content: encodedJsonToSend, contentContext: context, isComplete: true, completion: .idempotent)
} catch {
print("\(error)")
}
It works great, even for hundreds of file requests. The problem arises if some files being requested are extremely large, like 600MB. You can see the memory speedometer on the primary quickly ramp up to the yellow zone, at which point iOS kills the app for high memory use, and you see the Jetsam log.
I changed the code to skip JSON encoding the binary file as a test, and that helped a bit, but it still goes too high; the real offender is the step where it loads the 600MB file into the data var:
let data = try Data(contentsOf: filePath)
If I remark out everything else and just leave that one line, I can still see the memory use spike.
As a fix, I'm rewriting this so the secondary requests the file in 5MB chunks by telling the primary a byte range such as "0-5242880" or "5242881-10485760", and then reassembling the chunks on the secondary once they all come in. So far this seems promising, but it's a fair amount of work.
My question: Does Network Framework have a built-in way to stream those bytes straight from disk as it sends them? So that I could send all the data in one single request without having to load the bytes into memory?
I've been searching all over the web trying to find the proper way to get all records created by a specific user in CloudKit.
I am able to get the correct id using:
guard let userRecordID = try? await container.userRecordID() else { return }
I can see that the id returned is associated with records in my CloudKit dashboard. So I would expect that the following would get those records:
let predicate = NSPredicate(format: "%K == %@", #keyPath(CKRecord.creatorUserRecordID), userRecordID)
let query = CKQuery(recordType: "CKUser", predicate: predicate)
But instead when I use that query it returns nothing. It is successful but with nothing returned...
Any ideas why this would be happening?
P.S. I have also tried constructing the predicate using the reference, but I get the same result - success with no results.
P.S.2 Also worth mentioning that I am trying to get the results from the public database and I have set my CKContainer to the correct container id.
I'm continuing with the migration towards Swift 6. Within one of our libraries, I want to check whether a parameter object: Any? confirms to Sendable.
I tried the most obvious one:
if let sendable = object as? Sendable {
}
But that results into the compiler error "Marker protocol 'Sendable' cannot be used in a conditional cast".
Is there an other way to do this?
I have a macro that converts expression into a string literal, e.g.:
#toString(variable) -> "variable"
#toString(TypeName) -> "TypeName"
#toString(\TypeName.property) -> "property"
In Xcode 16.3 #toString(TypeName) stopped to work, compilation throws 'Expected member name or initializer call after type name' error.
Everything works fine in Xcode 16.2. I tried to compare build settings between 16.2 and 16.3 but haven't noticed differences that may cause this new error.
The following works in both Xcode versions:
#toString(variable) -> "variable"
#toString(\TypeName.property) -> "property"
Seems like Xcode tries to compile code that shouldn't be compiled because of macro expansion.
Does anybody know what new has appeared in 16.3 and, perhaps, how to fix the problem?
i have macos 15 and xcode 16 swift 6 and want to make apps
to run on macintosh.
i know the syntax of this programming language, but i need
informations like which libraries i have to import for func's
which name i do not know, and parameters i have not found
on websites or the tutorial on swift.
i need procedures like
open window at x,y,width,height
draw rectangle at x,y,width,height,color
draw text at x,y,width,height,color,size
read keyboard-letter,up/dn,shift
read mouse x,y,buttons
Topic:
Programming Languages
SubTopic:
Swift
Getting this error several times when presenting a modal window over my splitview window when running it on my Mac using Swift/Mac Catalyst in XCode 14.2. When I click the Cancel button in the window then I get Scene destruction request failed with error: (null) right after an unwind segue.
2023-07-04 16:50:45.488538-0500 Recipes[27836:1295134] [WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set.
2023-07-04 16:50:45.488972-0500 Recipes[27836:1295134] [WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set.
2023-07-04 16:50:45.496702-0500 Recipes[27836:1295134] [WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set.
2023-07-04 16:50:45.496800-0500 Recipes[27836:1295134] [WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set.
2023-07-04 16:50:45.994147-0500 Recipes[27836:1295134] Unbalanced calls to begin/end appearance transitions for <UINavigationController: 0x7f7fdf068a00>.
bleep
2023-07-04 16:51:00.655233-0500 Recipes[27836:1297298] Scene destruction request failed with error: (null)
I don't quite understand what all all this means. (The "bleep" was a debugging print code I put in the unwind segue). I'm working through Apple's Mac Catalyst tutorial but it seems to be riddled with bugs and coding issues, even in the final part of the completed app which I dowmloaded and ran. I don't see these problems on IPad simulator.
I don't know if it's because Catalyst has problems itself or there's something else going on that I can fix myself. Any insight into these errors would be very much appreciated!
PS: The app seems to run ok on Mac without crashing despite the muliple issues
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.
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.
Topic:
Programming Languages
SubTopic:
Swift
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<swift::RefCountBitsT<(swift::RefCountInlinedness)1>>::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, 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) -> () + 92 (<compiler-generated>:0)
15 Network 0x0000000185185df8 invocation function for block in nw_connection_group_handle_incoming_packet(NWConcrete_nw_connection_group*, NSObject<OS_nw_endpoint>*, NSObject<OS_nw_endpoint>*, NSObject<OS_nw_interface>*, 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?) -> Array<String> {
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 > 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?
Hey everyone,
I’m learning async/await and trying to fetch an image from a URL off the main thread to avoid overloading it, while updating the UI afterward. Before starting the fetch, I want to show a loading indicator (UI-related work). I’ve implemented this in two different ways using Task and Task.detached, and I have some doubts:
Is using Task { @MainActor the better approach?
I added @MainActor because, after await, the resumed execution might not return to the Task's original actor. Is this the right way to ensure UI updates are done safely?
Does calling fetchImage() on @MainActor force it to run entirely on the main thread?
I used an async data fetch function (not explicitly marked with any actor). If I were to use a completion handler instead, would the function run on the main thread?
Is using Task.detached overkill here?
I tried Task.detached to ensure the fetch runs on a non-main actor. However, it seems to involve unnecessary actor hopping since I still need to hop back to the main actor for UI updates. Is there any scenario where Task.detached would be a better fit?
class ViewController : UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
//MARK: First approch
Task{@MainActor in
showLoading()
let image = try? await fetchImage() //Will the image fetch happen on main thread?
updateImageView(image:image)
hideLoading()
}
//MARK: 2nd approch
Task{@MainActor in
showLoading()
let detachedTask = Task.detached{
try await self.fetchImage()
}
updateImageView(image:try? await detachedTask.value)
hideLoading()
}
}
func fetchImage() async throws -> UIImage {
let url = URL(string: "https://via.placeholder.com/600x400.png?text=Example+Image")!
//Async data function call
let (data, response) = try await URLSession.shared.data(from: url)
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
throw URLError(.badServerResponse)
}
guard let image = UIImage(data: data) else {
throw URLError(.cannotDecodeContentData)
}
return image
}
func showLoading(){
//Show Loader handling
}
func hideLoading(){
//Hides the loader
}
func updateImageView(image:UIImage?){
//Image view updated
}
}