Hello! I am working on a project that does some automatic code generation using SwiftSyntax and SwiftSyntaxBuilder. As part of this project, I want to put in a comment at the top of the file warning users to not modify the file and make it obvious that the code was automatically generated. I was trying to use the .lineComment(String) static member of the Trivia (or TriviaPiece) types and I expected that the comment would automatically be prefixed with the expected // and space for use in code. (For example, Trivia.lineComment("No comment") would be written as // No Comment when sent through a BasicFormat Object or similar SyntaxRewriter). I was surprised to find that this is not the case and was wondering before I write an issue on GitHub whether this behavior is intentional or a bug. If it is intentional, I'm not entirely sure if I'm missing something regarding this to more easily generate these comments.
At the moment my comment generation consists of constructing the comment in the leadingTrivia of the syntax node that appears after the comment. For example:
VariableDeclSyntax(leadingTrivia: [.newlines(2), .lineComment("// These members are always generated irrespective of the contents of the generated files. They are intended to exclusively centralize code symbols that would otherwise be repeated frequently."), .newlines(1)], modifiers: [DeclModifierSyntax(name: .keyword(.private)), DeclModifierSyntax(name: .keyword(.static))], .let, name: PatternSyntax(IdentifierPatternSyntax(identifier: "decoder")), initializer: InitializerClauseSyntax(value: ExprSyntax(stringLiteral: "\(configuration.decoderExpression)")))
outputs
// These members are always generated irrespective of the contents of the generated files. They are intended to exclusively centralize code symbols that would otherwise be repeated frequently.
private static let decoder = JSONDecoder()
in this project (with example data having been added).
Post
Replies
Boosts
Views
Activity
I'm working on Swift 6 concurrency support for our app.
I've always thought of NSAccessibilityElement as being like all of the other UI classes- only used (or usable) on the main thread. As far as I've seen, they are always called on the main thread.
But in Xcode 16 beta 2, it's only marked as Sendable but not MainActor.
Is that just an oversight or do we need to worry about these being used / called on threads?
It's easy enough to do the async work (well, not that easy), but I don't want to do all that work if Xcode 16 beta 3 is just going to add a MainActor to it. I've already been burned by that once, in WebKit- the first beta was missing several MainActor declarations, in places where it was unclear from the documentation.
I added a bunch of async fixes to my delegates, only to have to take it all out when the second Xcode beta shipped and the SDK headers changed.
How complete are the async declarations in the Xcode 16 SDKs?
Hello,
I want to use Automatic Grammar Agreement to localise a string in my app, let say "three remaining activities". The string "three" is obtained by using a NumberFormatter with a numberStyle set to .spellOut (so I'm not using an Integer)
var formatter: NumberFormatter = NumberFormatter()
formatter.numberStyle = .spellOut
let formattedCount: String = numberFormatter.string(from: count as NSNumber)!
Text("key_with_string_\(formattedCount)")
In my string catalog, I have translated the key key_with_string_%@ like this ^[%@ remaining activity](inflect: true), but it does not work.
I've tried to add the integer value used by the number formatter in the key key_with_string_%@_%lld but it does not work.
Should Automatic Grammar Agreement work normally just by using the formatted string provided by the NumberFormatter?
If not, is there a way to specify to use a secondary variable (my count integer) to switch between different categories like one and other automatically?
Thanks !
Axel
Hello everyone,
I'm encountering an issue with Swift and C++ interoperability when passing a void pointer between Swift and C++ functions. When I pass pMessageBuffer (an UnsafeMutableRawPointer) from Swift to MyCppClass.NFCompletion (a static c++ function), which expects a reference to void pointer, Swift throws an error "Cannot convert value of type 'UnsafeMutableRawPointer' to expected argument type 'Optional' ".
Here is a sample code to help in better visualization of the usecase.
Cpp Code
class MyCppClass {
public:
static void SendData(void *pMessage, TUInt16 pMessageLength) {
// Assume vSocket is my Swift object held in C++.
vSocket.Send(pMessage, pMessageLength);
}
static void NFCompletion(void * & pBuffer, TInt64 pErrorCode, VPtr pCompletionFunction) {
// Process the buffer.
}
};
Swift Code:
public class MySwiftClass {
var vConnection: NWConnection?
public init() {}
public func Send(_ pMessageBuffer: UnsafeMutableRawPointer, _ pMessageLength: TSUInt16) {
let messageData = Data(bytesNoCopy: pMessageBuffer, count: Int(pMessageLength), deallocator: .none)
self.vConnection?.send(content: messageData, completion: .contentProcessed { nw_error in
var error_code: TSInt64 = 0
if let nw_error = nw_error {
error_code = self.InternalGetNetworkErrorCode(nw_error)
}
// Here's where the issue arises:
MyCppClass.NFCompletion(pMessageBuffer, TInt64(error_code), self.uCompletionHandler)
})
}
// Example function to handle network errors
private func InternalGetNetworkErrorCode(_ error: Error) -> TSInt64 {
// Implementation to convert nw_error to TSInt64 error code
return 0 // Placeholder return value
}
}
Could someone please help me understand why this conversion error occurs? How should I correctly handle passing a void pointer between Swift and C++ functions, ensuring compatibility and proper memory management?
Note: TSInt64 is typealias for swift Int and TInt64 is alias of c++ int_64t.
Thank you in advance for your assistance!
Regards,
Harshal
I have a Matrix structure as defined below for working with 2D numerical data in Accelerate. The underlying numerical data in this Matrix struct is stored as an Array.
struct Matrix<T> {
let rows: Int
let columns: Int
var data: [T]
init(rows: Int, columns: Int, fill: T) {
self.rows = rows
self.columns = columns
self.data = Array(repeating: fill, count: rows * columns)
}
init(rows: Int, columns: Int, source: (inout UnsafeMutableBufferPointer<T>) -> Void) {
self.rows = rows
self.columns = columns
self.data = Array(unsafeUninitializedCapacity: rows * columns) { buffer, initializedCount in
source(&buffer)
initializedCount = rows * columns
}
}
subscript(row: Int, column: Int) -> T {
get { return self.data[(row * self.columns) + column] }
set { self.data[(row * self.columns) + column] = newValue }
}
}
Multiplication is implemented by the functions shown below.
import Accelerate
infix operator .*
func .* (lhs: Matrix<Double>, rhs: Matrix<Double>) -> Matrix<Double> {
precondition(lhs.rows == rhs.rows && lhs.columns == rhs.columns, "Matrices must have same dimensions")
let result = Matrix<Double>(rows: lhs.rows, columns: rhs.columns) { buffer in
vDSP.multiply(lhs.data, rhs.data, result: &buffer)
}
return result
}
func * (lhs: Matrix<Double>, rhs: Matrix<Double>) -> Matrix<Double> {
precondition(lhs.columns == rhs.rows, "Number of columns in left matrix must equal number of rows in right matrix")
var a = lhs.data
var b = rhs.data
let m = lhs.rows // number of rows in matrices A and C
let n = rhs.columns // number of columns in matrices B and C
let k = lhs.columns // number of columns in matrix A; number of rows in matrix B
let alpha = 1.0
let beta = 0.0
// matrix multiplication where C ← αAB + βC
let c = Matrix<Double>(rows: lhs.rows, columns: rhs.columns) { buffer in
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, alpha, &a, k, &b, n, beta, buffer.baseAddress, n)
}
return c
}
I can also define a Matrix structure where the underlying data is an UnsafeMutableBufferPointer. The buffer is handled by the MatrixData class.
struct Matrix<T> {
let rows: Int
let columns: Int
var data: MatrixData<T>
init(rows: Int, columns: Int, fill: T) {
self.rows = rows
self.columns = columns
self.data = MatrixData(count: rows * columns, fill: fill)
}
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
self.data = MatrixData(count: rows * columns)
}
subscript(row: Int, column: Int) -> T {
get { return self.data.buffer[(row * self.columns) + column] }
set { self.data.buffer[(row * self.columns) + column] = newValue }
}
}
class MatrixData<T> {
var buffer: UnsafeMutableBufferPointer<T>
var baseAddress: UnsafeMutablePointer<T> {
get { self.buffer.baseAddress! }
}
init(count: Int, fill: T) {
let start = UnsafeMutablePointer<T>.allocate(capacity: count)
self.buffer = UnsafeMutableBufferPointer(start: start, count: count)
self.buffer.initialize(repeating: fill)
}
init(count: Int) {
let start = UnsafeMutablePointer<T>.allocate(capacity: count)
self.buffer = UnsafeMutableBufferPointer(start: start, count: count)
}
deinit {
self.buffer.deinitialize()
self.buffer.deallocate()
}
}
Multiplication for this approach is implemented by the functions shown here.
import Accelerate
infix operator .*
func .* (lhs: Matrix<Double>, rhs: Matrix<Double>) -> Matrix<Double> {
precondition(lhs.rows == rhs.rows && lhs.columns == rhs.columns, "Matrices must have same dimensions")
let result = Matrix<Double>(rows: lhs.rows, columns: lhs.columns)
vDSP.multiply(lhs.data.buffer, rhs.data.buffer, result: &result.data.buffer)
return result
}
func * (lhs: Matrix<Double>, rhs: Matrix<Double>) -> Matrix<Double> {
precondition(lhs.columns == rhs.rows, "Number of columns in left matrix must equal number of rows in right matrix")
let a = lhs.data.baseAddress
let b = rhs.data.baseAddress
let m = lhs.rows // number of rows in matrices A and C
let n = rhs.columns // number of columns in matrices B and C
let k = lhs.columns // number of columns in matrix A; number of rows in matrix B
let alpha = 1.0
let beta = 0.0
// matrix multiplication where C ← αAB + βC
let c = Matrix<Double>(rows: lhs.rows, columns: rhs.columns)
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, alpha, a, k, b, n, beta, c.data.baseAddress, n)
return c
}
Both of these approaches give me similar performance. The only difference that I have noticed is the matrix buffer approach allows for reference semantics. For example, the code below uses half the memory with the matrix buffer approach compared to the matrix array approach. This is because b acts as a reference to a using the matrix buffer approach; otherwise, the matrix array approach makes a full copy of a.
let n = 10_000
let a = Matrix<Double>(rows: n, columns: n, fill: 0)
var b = a
b[0, 0] = 99
b[0, 1] = 22
Other than reference semantics, are there any reasons to use one of these approaches over the other?
Sorry this post is duplicate
Hello All, some background information first. I have the following struct:
Struct Category: Identifiable, Codeable, Hashable {
var id: UUID
var name: String
var subCategory: [Category]?
}
var categories: [Category]
There is no limit how many levels deep the subcategory can be. The user is essentially creating a hierarchical data filing system.
Given that the number of subCategory levels is unlimited, I am recursing over the subcategories to find the correct level at which to insert the newCategory.
The recursive function to add category is declared as:
func recursiveAddCategory(newCategory: Category, subCategoryOf: inout [Category]?)
you will note that I am trying to pass the subCategory as a reference (using inout), so that I can add to the original
and the function is called as recursiveAddCategory(newCategory, &categories.subCategory!)
the actual append statement within the recursiveAddCategory function is:
categories.subCategory?.append(newCategory)
I am encountering no errors but also find that the newCategory is not being added to the categories array.
Any help or guidance appreciated.
Thanks
I am working thru the issues of turning on Strict Concurrency Checking. I have a SwiftData application, and I am compressing images before saving them as data. My save function is pretty simple
private func save() {
ImageCompressor.compress(image: (frontImageSelected?.asUIImage())!, maxByte: 1_048_576) { image in
guard image != nil else {
print("Error compressing image")
return
}
if let greetingCard {
greetingCard.cardName = cardName
greetingCard.cardFront = image?.pngData()
greetingCard.cardManufacturer = cardManufacturer
greetingCard.cardURL = cardURL
greetingCard.eventType = eventType
} else {
let newGreetingCard = GreetingCard(cardName: cardName, cardFront: image?.pngData(), eventType: eventType, cardManufacturer: cardManufacturer, cardURL: cardURL)
modelContext.insert(newGreetingCard)
}
}
}
I compress the selected image, I had to change my ImageCompressor.compress closure to Sendable, but now every assignment above is flagging with the above warning. I define the greetingCard as var greetingCard: GreetingCard? in my view, since I can have it passed in for edit, or generated if new.
I also get the same warning on modelContext, which is defined as @Environment(\.modelContext) private var modelContext.
It's not clear to me how to address this warning. Any pointers would be helpful.
Hi,
When using Swift Concurrency blocking tasks like file I/O, GPU work and networking can prevent forward moving progress and have the potential to exhaust the cooperative thread pool and under utilize the CPU. It's been recommended to offload these tasks from the cooperative thread pool.
Is my understanding correct that the preferred way to do this is by creating async tasks via Dispatch or OperationQueue? And combining these with Continuations if a return value from the task is required? Or should I always be using Continuations in combination with Dispatch/OperationQueue?
There are also Executors but the documentation seems a bit limited on how to use these. The new TaskExecutor is also only available on the latest beta's.
My question is basically what is the recommend way to offload a task?
Thanks!
struct Preview: View {
private static let NAME = "Test"
@Query(filter: #Predicate<Item> { $0.name == Preview.NAME})
private var items: [Item]
var body: some View {
MyView(name: Preview.NAME, items: items)
}
}
Compile error occurs: key path cannot refer to static member 'NAME'
How can a (static) constant be referred in member closure?
In my method moveSun() it successfully rotates and plays the sound the first time it is called. However, subsequent calls to the method only play the sound and do not execute the rotate action. Does anyone know what may be causing this? Here's the relevant code:
func moveSun()
{
print(sunMoving)
let rotateAction = SKAction.rotate(toAngle: 2 * CGFloat.pi, duration: 2)
let playGearSound = SKAction.playSoundFileNamed("spinningGear", waitForCompletion: true)
let rotateAndPlayGearSound = SKAction.group([rotateAction, playGearSound])
sun.run(rotateAndPlayGearSound, completion: { self.sunMoving = false; print("completed completion handler") })
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
for t in touches
{
self.touchDown(atPoint: t.location(in: self))
}
}
func touchDown(atPoint pos : CGPoint)
{
let touchedNodes = nodes(at: pos)
for touchedNode in touchedNodes
{
print("touchNode: \(String(describing: touchedNode.name))")
if touchedNode.name == "sun" && !sunMoving
{
sunMoving = true
moveSun()
}
}
}
I have the following var in an @Observable class:
var displayResult: String {
if let currentResult = currentResult, let decimalResult = Decimal(string: currentResult) {
let result = decimalResult.formatForDisplay()
UIAccessibility.post(notification: .announcement, argument: "Current result \(result)")
return result
} else {
return "0"
}
}
The UIAccessiblity.post gives me this warning:
Reference to static property 'announcement' is not concurrency-safe because it involves shared mutable state; this is an error in Swift 6
How can I avoid this?
I'm trying to migrate my fairly large application to Swift Concurrency. I've have a class marked as @MainActor that sub-classes a 3rd party abstract class that is not migrated to Swift Concurrency.
I get the following error:
Main actor-isolated class 'MyClass' has different actor isolation from nonisolated superclass 'OtherAbstractClass'; this is an error in the Swift 6 language mode
My class needs to be MainActor as it uses other code that is required to be on the MainActor.
I can't see how to suppress this warning, I know as a guarantee that the abstract class will always be on the main thread so I need a way of telling the compiler that when I don't own the 3rd party code.
import OtherAbstractModule
@MainActor
class MyClass: OtherAbstractClass {
....
}
How can I satisfy the compiler in this case?
Currently Swift Testing has much less features than XCTest, so the adoption will be very slow from our side. Notable features we miss are UI tests, performance tests and attachments.
I did not want to create many issues in Swift Testing GitHub project as lots of these shortcoming are most probably tracked internally (I can see lots of references to radars in GitHub issues.)
So, my question is: Is it a good idea to wait with wider adoption or should we experiment with other tools like swift Benchmarks?
import Foundation
let formatter = DateFormatter()
let displayLocalFormat = true or false
let timeZone = UTC
let dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let currentDate = Date()
formatter.locale = displayLocalFormat ? Locale.current : Locale(identifier: "en_US_POSIX")
formatter.dateFormat = dateFormat
formatter.timeZone = timeZone
formatter.string(from: date) // This function returns date format 2024-05-23T11:16:24.706 a.m.Z
Why is "Go small with embedded Swift" still not available, despite the fact all the other WWDC24 Tuesday session videos are?
Hello,
I develop an HCE payment app.
In this app I can redirect users in Settings to set the default payment app
UIApplication.shared.open(URL(string: "App-prefs:General&path=CONTACTLESS_NFC")
But is it possible to know which app is selected or if my app is already set as default ?
I have a public swift function with the below declaration :
public func InternalMain (_ pNumOfArgs : Int32, _ pCmdlineArgs : UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>) -> Int32 {..}
I need this function as public because I need to invoke in from a different library. But the above declaration produces an error in my generated swift header i.e '-swift.h' file because 'UnsafeMutablePointer<UnsafeMutablePointer?>' type cannot be represented in the swift generated header.
Can someone help how do I get past this. This is a class independent function and I tried using the '@nonobj' to prevent this from getting in the generated header but it still gives an error.
When we pass some special words, NSString.getBytes does not crash even when we pass an invalid range.
It seems a bug.
The below code is an example.
func testNSStringGetBytes() {
let originalString: String = "あ"
let bufferSize = 256
var buffer = [UInt8](repeating: 0, count: bufferSize)
var usedLength = 0
// An invalid range is passed
let range = NSRange(location: 0, length: originalString.count + 1)
var remainingRange = NSRange()
(originalString as NSString)
.getBytes(
&buffer,
maxLength: bufferSize,
usedLength: &usedLength,
encoding: String.Encoding.utf8.rawValue,
options: [],
range: range,
remaining: &remainingRange
)
print("Used Length: \(usedLength)")
print("Buffer: \(buffer[0..<usedLength])")
if remainingRange.length > 0 {
print("Did not convert the whole string. Remaining range: \(remainingRange)")
} else {
print("Entire string was converted successfully.")
}
}
In app delegate I'm trying to load an array with strings from a plist. I print the plist it prints fine...
func loadTypesArray() {
guard let path = Bundle.main.path(forResource: "Types", ofType: "plist") else {return}
let url = URL(fileURLWithPath: path)
let data = try! Data(contentsOf: url)
guard let plist = try! PropertyListSerialization.propertyList(from: data, options: .mutableContainers, format: nil) as? [String] else {return}
print(plist)
typesArray = plist
// print(typesArray)
}
But when I try and access it from a different part of the app using let typesArray = AppDelegate().typesArray
the array I get is an empty array! any help?