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
Dive into the world of programming languages used for app development.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
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
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
Topic:
Programming Languages
SubTopic:
General
Tags:
Objective-C Runtime
Xcode Sanitizers and Runtime Issues
Foundation
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
Topic:
Programming Languages
SubTopic:
Swift
I came across
One Sided Range
Example:
[...2]
[2...]
[..<2]
Half Open Range
[..<2]
Can not the last use case be separated [..<2] of One Sided Range for Brevity as it is already included in Half Open Range?
I was trying to evaulate
let myTuple = ("blue", false)
let otherTuple = ("blue", true)
if myTuple < otherTuple {
print("yes it evaluates")
}
Ans I got
/tmp/S9jAk7P7KW/main.swift:5:12: error: binary operator '<' cannot be applied to two '(String, Bool)' operands
if myTuple < 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
A few questions. One, can I safely upgrade to my project to Swift 6.2 without having to require iOS 26+? Two, where do I actually make the upgrade. This is what I see in build settings:
6.2 is not available in the dropdown?
Why Ternary operator in not called a binary Operator or ternary Operands ?
question ? answer1 : answer2
When it takes 2 operators ?
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.
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'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?
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.
func textField(
_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String
) -> 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?
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!
I’ve been struggling with this issue for a long time. When I try to archive my app to submit it to the App Store, I encounter two errors:
Linker command failed with exit code 1 (use -v to see invocation)
Linker command failed with exit code 1 (use -v to see invocation)
Topic:
Programming Languages
SubTopic:
Swift
I've been testing my open source libraries with Swift 6.2 and the new Default Actor Isolation concurrency build setting set to MainActor (with Complete strict concurrency turned on). My library Destinations uses protocols extensively, often applying conformance to foundational Swift protocols like Hashable and Identifiable. Many of these basic protocols are not flagged as running on the @MainActor in Beta 1, leading to situations like this:
Given this example code:
public protocol Contentable: Identifiable {
var id: UUID { get }
}
final class ContentModel: Contentable {
let id: UUID = UUID()
}
I get the warning:
Multiline
Conformance of 'ContentModel' to protocol 'Contentable' crosses into main actor-isolated code and can cause data races; this is an error in the Swift 6 language mode
The fix it suggests is to put a @MainActor before the Contentable protocol declaration in ContentModel, which seems to be a new attribute configuration in Swift 6.2. This solves the warning, but would create a lot of extra noise across the codebase.
Was it an oversight or a temporary omission that protocols like Hashable and Identifiable do not run on @MainActor by default, or is there some other reason they are excluded? Considering how often protocols in our code may conform to foundational protocols like this, it seems at odds to the MainActor mode of the Default Actor Isolation setting given that it was created to make concurrency easier and less boilerplate to implement.
我的应用是在mac intel时发生这个问题,从dump看程序一直卡在mmap_locked,不知要怎么修改
程序dump如下
amaran.txt
Topic:
Programming Languages
SubTopic:
General
Hey everyone,
I have a problem with an app im creating. The code doesn't have any errors but the console has this that pops up:
Snapshot request 0x1054191d0 complete with error: <NSError: 0x10541a970; domain: FBSSceneSnapshotErrorDomain; code: 4; "an unrelated condition or state was not satisfied"> {
NSLocalizedDescription = an error occurred during a scene snapshotting operation;
}
With Swift being brought to new places, is anyone working on interoperability with PHP? I'd love to replace much of my PHP and Javascript web code with Swift (and ideally SwiftUI for UI design). Are there any projects/people working in this space?
Hi,
I’m trying to use the new InlineArray type, but noticed that it is unfortunately only available on macOS 26 and not on macOS 15 and others. As this is quite an essential type, I was wondering if this is intended or will this change in later beta’s? Not having it available on older Darwin platforms would severily limit it’s usage in the coming years.
Thanks!