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?
Post
Replies
Boosts
Views
Activity
I had a series of @Model classes with some mandatory attributes and some optional.
Pre-move to 18, everything was working fine. After the migration, it reports that every single non-Optional attribute is nil upon trying to save.
The error is CoreData related but not sure if its in the Core layer or Swift layer.
Sample error (with app data removed) is :
SwiftData.DefaultStore save failed with error: Error Domain=NSCocoaErrorDomain Code=1560 "Multiple validation errors occurred."
Error Domain=NSCocoaErrorDomain Code=1570 \"%{PROPERTY}@ is a required value.\" UserInfo={NSValidationErrorObject=<NSManagedObject: 0x30388b2a0>
NSLocalizedDescription=%{PROPERTY}@ is a required value., NSValidationErrorKey=systemName, NSValidationErrorValue=null}"
I have modified the code to provide default values for all constructors in an attempt to see a difference, but get the same errors
With the integration of Apple's pushToTalk framework - we create the PTChannelManager using its async initializer from AppDidFinishLaunching - using an actor to ensure the PTChannelManager is only created once.
With this we have been seeing a lot of crashes for users in our analytics dashboards happening about ~2 seconds after app launch around a task-dealloc.
Here is a simplified version of our actor and Manager - where the manager just shows the init. The init of it is an async optional init because the creation of the PTChannelManager uses an async throws.
actor PushToTalkDeviceContainer {
private var internalPushToTalkManagerTask: Task<PushToTalkManager?, Never>?
func pushToTalkManager() async -> PushToTalkManager? {
#if !os(visionOS)
if let internalPushToTalkManagerTask {
return await internalPushToTalkManagerTask.value
}
let internalPushToTalkManagerTask = Task<PushToTalkManager?, Never> {
return await PushToTalkManagerImp()
}
self.internalPushToTalkManagerTask = internalPushToTalkManagerTask
return await internalPushToTalkManagerTask.value
#else
return nil
#endif
}
}
public class PushToTalkManagerImp: PushToTalkManager {
public let onPushToTalkDelegationEvent: AnyPublisher<PushToTalkDelegationEvent, Never>
public let onPushToTalkAudioSessionChange: AnyPublisher<PushToTalkManagerAudioSessionChange, Never>
public let onChannelRestoration: AnyPublisher<UUID, Never>
private let ptChannelManager: PTChannelManager
private let restorationDelegate: PushToTalkRestorationDelegate
private let delegate: PushToTalkDelegate
init?() async {
self.delegate = PushToTalkDelegate()
self.restorationDelegate = PushToTalkRestorationDelegate()
self.onPushToTalkDelegationEvent = delegate.pushToTalkDelegationSubject.eraseToAnyPublisher()
self.onPushToTalkAudioSessionChange = delegate.audioSessionSubject.eraseToAnyPublisher()
self.onChannelRestoration = restorationDelegate.restorationDelegateSubject.eraseToAnyPublisher()
do {
ptChannelManager = try await PTChannelManager.channelManager(delegate: delegate, restorationDelegate: restorationDelegate)
} catch {
return nil
}
}
}
The crash stack trace is as follows:
0 libsystem_kernel.dylib 0x00000001e903342c __pthread_kill + 8 (:-1)
1 libsystem_pthread.dylib 0x00000001fcdd2c0c pthread_kill + 268 (pthread.c:1721)
2 libsystem_c.dylib 0x00000001a7ed6c34 __abort + 136 (abort.c:159)
3 libsystem_c.dylib 0x00000001a7ed6bac abort + 192 (abort.c:126)
4 libswift_Concurrency.dylib 0x00000001ab2bf7c8 swift::swift_Concurrency_fatalErrorv(unsigned int, char const*, char*) + 32 (Error.cpp:25)
5 libswift_Concurrency.dylib 0x00000001ab2bf7e8 swift::swift_Concurrency_fatalError(unsigned int, char const*, ...) + 32 (Error.cpp:35)
6 libswift_Concurrency.dylib 0x00000001ab2c39a8 swift_task_dealloc + 128 (TaskAlloc.cpp:59)
7 MyApp 0x0000000104908e04 PushToTalkManagerImp.__allocating_init() + 40 (PushToTalkManager.swift:0)
8 MyApp 0x0000000104908e04 closure #1 in PushToTalkDeviceContainer.pushToTalkManager() + 60
9 MyApp 0x00000001041882e9 specialized thunk for @escaping @callee_guaranteed @Sendable @async () -> (@out A) + 1 (<compiler-generated>:0)
10 MyApp 0x0000000103a652bd partial apply for specialized thunk for @escaping @callee_guaranteed @Sendable @async () -> (@out A) + 1 (<compiler-generated>:0)
11 libswift_Concurrency.dylib 0x00000001ab2c2775 completeTaskWithClosure(swift::AsyncContext*, swift::SwiftError*) + 1 (Task.cpp:463)
I have an app that uses a MultiCamCaptureSession, the devices of which are builtInUltraWideCamera and builtInLiDARDepthCamera cameras. Occasionally when outside I get some frame drops due to discontinuity that end in the media services being reset:
[06-24 11:27:13][CameraSession] Capture session runtime error: related decl 'e' for AVError(_nsError: Error Domain=AVFoundationErrorDomain Code=-11819 "Cannot Complete Action" UserInfo={NSLocalizedDescription=Cannot Complete Action, NSLocalizedRecoverySuggestion=Try again later.})
This runtime error notification is always superseded by 4-5 frame drops :
[06-24 11:27:10][CaptureSession] Dropped frame because Discontinuity
Logging the system temperature shows
[06-24 11:27:10][CaptureSession] Temperature is 'Fair'
I have some inclination that the frame discontinuity is being caused by the whileBalanceMode of the capture session, perhaps the algorithm requires 5 recent frames to work. I had a similar problem with the lidar depth camera where with filtering enabled exactly 5 frame drops would make the media services reset.
When the whiteBalanceMode is locked I do slightly better with 10 frame drops before the mediaServices are reset.
Is there any logging utility to determine the actual reason? All of these sampleBuffers come with no info attachment only the not so useful "Dropped frame because Discontinuity." Any ideas for solving this would be helpful as well. Maybe tuning the camera to work better with quickly varying lighting conditions?
Staring to use ScriptingBridge in Swift to enable faster scripting access to an external app (Devonthink) and therefore avoid having to use an AppleScript as a conduit to call a Swift command line utility and deal with its results.
The plan is to be able to read the plaintext of a record (no problem) and change the record name in Devonthink based on its contents. But I can’t seem to write to a property, instead getting an error “Cannot assign to property: ‘***’ is immutable”.
Any guidance how to get around this?
When user triggers a sheet of a view, it's quite easy to deal with its confirmation action. However, how can I deal with the cancellation action, which means when user taps the cancel button, what they edits can re-become its original version ( I am using SwiftData)?
Hello, I'm a beginner and have started learning Swift. I want to create a toy CLI project that needs to read the arguments you pass to it, but I'm unable to figure out how I can run this project from the CLI so I can actually pass arguments to my program. Any idea?
Hello everyone,
I’m encountering an issue with my Swift Testing suite where state changes made in one test method do not persist to another. I am using Swift’s @Suite and @Test annotations to group and serialize my tests, but it seems that the state is not being carried over between the tests. The second function fails with:
Expectation failed: (string → nil) != nil
Here is my example code:
import Testing
@Suite(.serialized)
struct createCheckTests {
var value = 25
var string: String? = nil
@Test("Create string")
mutating func stringCreation() {
#expect(value > 0)
string = "Value is: \(value)"
}
@Test("Check string")
func stringCheck() {
#expect(string != nil, "The string is nil")
print("\(String(describing: string))")
}
}
What is the correct way to approach such a scenario where I want to test two functions that are related, one to generate some value and one to check that generated value against it initial value using Suites to group and isolate them from other tests?
Thanks.
For some reason, every time I'm accessing a view populated with posts and fetching posts, my app has like a 5-8 second hang time. I don't know whats causing this issue, and I have been dealing with this for 3 days.
`func fetchPosts(completion: @escaping (Result<[PostWithUser], Error>) -> Void) {
if !cachedPosts.isEmpty {
completion(.success(self.cachedPosts))
return
}
postsRef.order(by: "timestamp", descending: true).getDocuments { [weak self] snapshot, error in
guard let self = self else { return }
if let error = error {
completion(.failure(error))
return
}
guard let documents = snapshot?.documents else {
completion(.success([]))
return
}
let group = DispatchGroup()
var postsWithUsers: [PostWithUser] = []
DispatchQueue.global(qos: .userInitiated).async {
for document in documents {
group.enter()
let data = document.data()
guard let userId = data["userId"] as? String,
let parentId = data["parentId"] as? String,
let groupId = data["groupId"] as? String,
let text = data["text"] as? String,
let isPinned = data["isPinned"] as? Bool,
let imageUrl = data["imageUrl"] as? String,
let videoUrl = data["videoUrl"] as? String,
let timestamp = data["timestamp"] as? Timestamp,
let views = data["views"] as? Int else {
group.leave()
continue
}
let post = Post(id: document.documentID, userId: userId, parentId: parentId, groupId: groupId, text: text, imageUrl: imageUrl, videoUrl: videoUrl, timestamp: timestamp.dateValue(), isPinned: isPinned, likedBy: [], views: views)
self.usersRef.document(userId).getDocument { userDocument, error in
defer { group.leave() }
if let userDocument = userDocument, let userData = userDocument.data() {
let user = User(
id: userId,
username: userData["username"] as? String ?? "",
bio: userData["bio"] as? String ?? "",
profilePictureUrl: userData["profileImageUrl"] as? String ?? "",
privateProfile: userData["privateProfile"] as? Bool ?? false,
privateFollowerList: userData["privateFollowerList"] as? Bool ?? false,
privateFollowingList: userData["privateFollowingList"] as? Bool ?? false,
privateReplies: userData["privateReplies"] as? Bool ?? false,
privateLikes: userData["privateLikes"] as? Bool ?? false
)
let postWithUser = PostWithUser(post: post, user: user)
DispatchQueue.main.async {
postsWithUsers.append(postWithUser)
}
} else {
print("Failed to fetch user data for userId: \(userId), error: \(String(describing: error))")
}
}
}
group.notify(queue: .main) {
self.cachedPosts = postsWithUsers
completion(.success(postsWithUsers))
}
}
}
}`
`
func fetchPosts() {
PostService.shared.fetchPosts { result in
switch result {
case .success(let posts):
DispatchQueue.main.async {
self.posts = posts
}
case .failure(let error):
print("Failed to fetch posts: \(error)")
}
}
}
func refreshPosts() {
PostService.shared.refreshPosts { result in
switch result {
case .success(let posts):
DispatchQueue.main.async {
self.posts = posts
}
case .failure(let error):
print("Failed to fetch posts: \(error)")
}
}
}
I have encountered an issue that when using a ModelActor to sync data in the background, the app will crash if one of the operations is to remove a PersistentModel from the context.
This is running on the latest beta of Xcode 16 with visionOS 1.2 as target and in Swift 6 language mode.
The code is being executed in a ModelActor.
The error is first thrown by:
#5 0x00000001c3223280 in PersistentModel.getValue<τ_0_0>(forKey:) ()
Thread 1: Fatal error: Context is missing for Optional(SwiftData.PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: x-coredata://97AA86BC-475D-4509-9004-D1182ABA1922/Reminder/p303), implementation: SwiftData.PersistentIdentifierImplementation))
func globalSync() async {
await fetchAndSyncFolders()
let result = await fetchReminders()
switch result {
case .success(let ekReminders):
var localReminders = (try? await fetch(FetchDescriptor<Reminder>())) ?? []
// Handle local reminders with nil ekReminderID by creating new EKReminders for them
for reminder in localReminders {
if reminder.ekReminderID == nil {
await self.createEkReminder(reminder: reminder)
}
}
// Re-fetch local reminders to include newly created EKReminderIDs
localReminders = (try? await fetch(FetchDescriptor<Reminder>())) ?? []
var localReminderDict = [String: Reminder]()
for reminder in localReminders {
if let ekReminderID = reminder.ekReminderID {
if let existingReminder = localReminderDict[ekReminderID] {
self.delete(model: existingReminder)
} else {
localReminderDict[ekReminderID] = reminder
}
}
}
let ekReminderDict = createReminderLookup(byID: ekReminders)
await self.syncReminders(localReminders: Array(localReminderDict.values), localReminderDict: localReminderDict, ekReminderDict: ekReminderDict)
// Merge duplicates
await self.mergeDuplicates(localReminders: localReminders)
save()
case .failure(let error):
print("Failed to fetch reminders: \(error.localizedDescription)")
}
}
Sorry this post is duplicate
Good morning,
I've developed an application where we download a JSON of objects and we store those information on a CoreData table.
We've also created a Collection view used to show those information through a NSFetchedResultsController.
Can someone helps me to understand the reason why I get this issue?
Thanks indeed
Fatal Exception: NSInvalidArgumentException
0 CoreFoundation 0x83f20 __exceptionPreprocess
1 libobjc.A.dylib 0x16018 objc_exception_throw
2 CoreFoundation 0x1b6250 _NSArrayRaiseInsertNilException
3 CoreFoundation 0x16f5c -[__NSCFArray objectAtIndex:]
4 CoreData 0x13af14 -[_PFMutableProxyArray subarrayWithRange:]
5 CoreData 0xc4948 -[_NSDefaultSectionInfo objects]
6 CoreData 0x9c3fc -[NSFetchedResultsController _conditionallyDispatchSnapshotToDelegate:updatesInfo:]
7 CoreData 0x6d4ec __82-[NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:]_block_invoke
8 CoreData 0x270dc developerSubmittedBlockToNSManagedObjectContextPerform
9 CoreData 0x9d0ec -[NSManagedObjectContext performBlockAndWait:]
10 CoreData 0x9c6e8 -[NSFetchedResultsController _core_managedObjectContextDidChange:]
11 CoreFoundation 0x5178c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__
12 CoreFoundation 0x516a8 ___CFXRegistrationPost_block_invoke
13 CoreFoundation 0x515f0 _CFXRegistrationPost
14 CoreFoundation 0x4fbb8 _CFXNotificationPost
15 Foundation 0x31574 -[NSNotificationCenter postNotificationName:object:userInfo:]
16 CoreData 0x6a548 -[NSManagedObjectContext _createAndPostChangeNotification:deletions:updates:refreshes:deferrals:wasMerge:]
17 CoreData 0x69d10 -[NSManagedObjectContext _postRefreshedObjectsNotificationAndClearList]
18 CoreData 0x68a4c -[NSManagedObjectContext _processRecentChanges:]
19 CoreData 0x91494 -[NSManagedObjectContext _coreMergeChangesFromDidSaveDictionary:usingObjectIDs:withClientQueryGeneration:]
20 CoreData 0x90334 -[NSManagedObjectContext mergeChangesFromContextDidSaveNotification:]
21 CoreData 0x270dc developerSubmittedBlockToNSManagedObjectContextPerform
22 libdispatch.dylib 0x3dd4 _dispatch_client_callout
23 libdispatch.dylib 0x125a4 _dispatch_main_queue_drain
24 libdispatch.dylib 0x121b8 _dispatch_main_queue_callback_4CF
25 CoreFoundation 0x56710 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__
26 CoreFoundation 0x53914 __CFRunLoopRun
27 CoreFoundation 0x52cd8 CFRunLoopRunSpecific
28 GraphicsServices 0x11a8 GSEventRunModal
29 UIKitCore 0x40a90c -[UIApplication _run]
30 UIKitCore 0x4be9d0 UIApplicationMain
31 Rainbow 0x80c0 main + 15 (main.swift:15)
32 ??? 0x1b3419e4c (Mancante)
Good morning,
I've developed an application in order to show the information stored into a CoraData Table on a CollectionView through a NSFetchedResultsController. Several times I got this issue, is there anyone who can help me to understand the reason why this happens?
Thanks indeed.
Fatal Exception: NSInvalidArgumentException
0 CoreFoundation 0x83f20 __exceptionPreprocess
1 libobjc.A.dylib 0x16018 objc_exception_throw
2 CoreFoundation 0x1b6250 _NSArrayRaiseInsertNilException
3 CoreFoundation 0x16f5c -[__NSCFArray objectAtIndex:]
4 CoreData 0x13af14 -[_PFMutableProxyArray subarrayWithRange:]
5 CoreData 0xc4948 -[_NSDefaultSectionInfo objects]
6 CoreData 0x9c3fc -[NSFetchedResultsController _conditionallyDispatchSnapshotToDelegate:updatesInfo:]
7 CoreData 0x6d4ec __82-[NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:]_block_invoke
8 CoreData 0x270dc developerSubmittedBlockToNSManagedObjectContextPerform
9 CoreData 0x9d0ec -[NSManagedObjectContext performBlockAndWait:]
10 CoreData 0x9c6e8 -[NSFetchedResultsController _core_managedObjectContextDidChange:]
11 CoreFoundation 0x5178c CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER
12 CoreFoundation 0x516a8 ___CFXRegistrationPost_block_invoke
13 CoreFoundation 0x515f0 _CFXRegistrationPost
14 CoreFoundation 0x4fbb8 _CFXNotificationPost
15 Foundation 0x31574 -[NSNotificationCenter postNotificationName:object:userInfo:]
16 CoreData 0x6a548 -[NSManagedObjectContext _createAndPostChangeNotification:deletions:updates:refreshes:deferrals:wasMerge:]
17 CoreData 0x69d10 -[NSManagedObjectContext _postRefreshedObjectsNotificationAndClearList]
18 CoreData 0x68a4c -[NSManagedObjectContext _processRecentChanges:]
19 CoreData 0x91494 -[NSManagedObjectContext _coreMergeChangesFromDidSaveDictionary:usingObjectIDs:withClientQueryGeneration:]
20 CoreData 0x90334 -[NSManagedObjectContext mergeChangesFromContextDidSaveNotification:]
21 CoreData 0x270dc developerSubmittedBlockToNSManagedObjectContextPerform
22 libdispatch.dylib 0x3dd4 _dispatch_client_callout
23 libdispatch.dylib 0x125a4 _dispatch_main_queue_drain
24 libdispatch.dylib 0x121b8 _dispatch_main_queue_callback_4CF
25 CoreFoundation 0x56710 CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE
26 CoreFoundation 0x53914 __CFRunLoopRun
27 CoreFoundation 0x52cd8 CFRunLoopRunSpecific
28 GraphicsServices 0x11a8 GSEventRunModal
29 UIKitCore 0x40a90c -[UIApplication _run]
30 UIKitCore 0x4be9d0 UIApplicationMain
31 Cloud 0x80c0 main + 15 (main.swift:15)
32 ??? 0x1b3419e4c (Mancante)
Hi guys,
🙏I have a problem with repeated saving to the database. If I do the first update it is OK, but after the second attempt the update fails and the console says "Failed to commit transaction: database is locked".
Here is my function:
func updateMapCoordinates(radius: Int32) {
// Otevření databáze, pokud není otevřená
guard db != nil else {
print("Database connection is nil")
return
}
var statement: OpaquePointer? = nil
let updateQuery = "UPDATE \(mapTable) SET radius = ? WHERE id = 1;"
// Začátek transakce
if sqlite3_exec(db, "BEGIN TRANSACTION", nil, nil, nil) != SQLITE_OK {
let errorMessage = String(cString: sqlite3_errmsg(db))
print("Failed to begin transaction: \(errorMessage)")
return
}
if sqlite3_prepare_v2(db, updateQuery, -1, &statement, nil) == SQLITE_OK {
sqlite3_bind_int(statement, 1, radius)
print("uložím \(radius)")
if sqlite3_step(statement) == SQLITE_DONE {
print("Coordinates saved successfully")
} else {
let errorMessage = String(cString: sqlite3_errmsg(db))
print("Failed to save coordinates: \(errorMessage)")
}
} else {
let errorMessage = String(cString: sqlite3_errmsg(db))
print("SAVE statement could not be prepared: \(errorMessage)")
}
// Finalizace statementu
sqlite3_finalize(statement)
// Ukončení transakce
if sqlite3_exec(db, "COMMIT", nil, nil, nil) != SQLITE_OK {
let errorMessage = String(cString: sqlite3_errmsg(db))
print("Failed to commit transaction: \(errorMessage)")
sqlite3_exec(db, "ROLLBACK", nil, nil, nil)
}
}
Using Charts in SwiftUI to create a horizontal bar chart, if the text of the legend is sufficiently long, the text overflows outside of the view rather than wrapping or moving to the next line. (can see problem when running code on on iPhone)
Is this a bug or am I doing something incorrectly?
I can use .clipped() to ensure the legend doesn't overflow. But that doesn't fully solve the problem because the text is then just cut off.
import Charts
import SwiftUI
struct ChartData: Identifiable {
let id: Int
let title: String
let count: Double
let color: Color
}
struct ContentView: View {
private let data = [
ChartData(id: 1, title: "Item 1", count: 4, color: .yellow),
ChartData(id: 2, title: "Item 2 With a Long Title and then some more", count: 6, color: .blue),
ChartData(id: 3, title: "Item 3 With a Long Title", count: 12, color: .green)
]
private let chartHeight: CGFloat = 40
private let chartCornerRadius: CGFloat = 5
var body: some View {
VStack {
Chart(data) { item in
BarMark(
x: .value("Count", item.count),
stacking: .normalized
)
.foregroundStyle(by: .value("Title", item.title))
}
.chartXAxis(.hidden)
.chartYAxis(.hidden)
.chartLegend(.visible)
.chartPlotStyle { chartContent in
chartContent
.frame(height: chartHeight)
}
.chartForegroundStyleScale(range: data.map { $0.color })
}
.padding()
}
}
#Preview {
ContentView()
}
iOS 18 App Intents while supporting iOS 17
Hello,
I have an existing app that supports iOS 17. I already have three App Intents but would like to add some of the new iOS 18 app intents like ShowInAppSearchResultsIntent.
However, I am having a hard time using #available or @available to limit this ShowInAppSearchResultsIntent to iOS 18 only while still supporting iOS 17.
Obviously, the ShowInAppSearchResultsIntent needs to use @AssistantIntent which is iOS 18 only, so I mark that struct as @available(iOS 18, *). That works as expected. It is when I need to add this "SearchSnippetIntent" intent to the AppShortcutsProvider, that I begin to have trouble doing. See code below:
struct SnippetsShortcutsAppShortcutsProvider: AppShortcutsProvider {
@AppShortcutsBuilder
static var appShortcuts: [AppShortcut] {
//iOS 17+
AppShortcut(intent: SnippetsNewSnippetShortcutsAppIntent(), phrases: [
"Create a New Snippet in \(.applicationName) Studio",
], shortTitle: "New Snippet", systemImageName: "rectangle.fill.on.rectangle.angled.fill")
AppShortcut(intent: SnippetsNewLanguageShortcutsAppIntent(), phrases: [
"Create a New Language in \(.applicationName) Studio",
], shortTitle: "New Language", systemImageName: "curlybraces")
AppShortcut(intent: SnippetsNewTagShortcutsAppIntent(), phrases: [
"Create a New Tag in \(.applicationName) Studio",
], shortTitle: "New Tag", systemImageName: "tag.fill")
//iOS 18 Only
AppShortcut(intent: SearchSnippetIntent(), phrases: [
"Search \(.applicationName) Studio",
"Search \(.applicationName)"
], shortTitle: "Search", systemImageName: "magnifyingglass")
}
let shortcutTileColor: ShortcutTileColor = .blue
}
The iOS 18 Only AppShortcut shows the following error but none of the options seem to work. Maybe I am going about it the wrong way.
'SearchSnippetIntent' is only available in iOS 18 or newer
Add 'if #available' version check
Add @available attribute to enclosing static property
Add @available attribute to enclosing struct
Thanks in advance for your help.
We have a feature requirement where we need to use LazyVGrid and DropDelegate. Our view hierarchy is as follows:
Color.white.ignoresSafeArea()
VStack(spacing: 0) {
customNavigationView
ScrollView(showsIndicators: true) {
LazyVGrid(columns: columns,
alignment: .center,
spacing: 16) {
ForEach(viewModel.selectedReferences, id: \.self) { item in
ZStack {
Rectangle()
.fill(Color.yellow.opacity(0.5))
Text(item.title)
}
.frame (height: 120)
.background(Color.white)
.padding([.leading, .trailing], 4)
.overlay((draggedItem?.uuid == item.uuid && changedView) ? Color.white.opacity(0.8) : Color.clear)
.clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
.onDrag {
initialIndex = viewModel.selectedReferences.firstIndex { $0 == item }
draggedItem = item
changedView = false
return NSItemProvider(object: String(item.uuid) as NSString)
}
.clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
.onDrop(of: [UTType.text], delegate: DragRelocateDelegate(item: item,
listData: $viewModel.selectedReferences,
current: $draggedItem,
changedView: $changedView) { endIndex in
})
}
}
.animation(.default, value: viewModel.selectedReferences)
}
.frame(width:(UIScreen.main.bounds.width))
.onDrop(of: [UTType.text], delegate: DropOutsideDelegate(current: $draggedItem, changedView: $changedView))
bottomBarView
}
.frame(maxWidth: .infinity)
}
While performing a reshuffle, auto-scroll works within the bounds of the ScrollView content. However, according to the feature requirement, auto-scroll should also work when we place an uplifted view at the top or bottom of the view.
STEPS TO REPRODUCE
Launch the demo.
Scroll to the bottom of the LazyVGrid.
Pick any item using the DropDelegate.
Try to place that uplifted view on the custom navigation view.
Expected Result:
The ScrollView should auto-scroll.
Actual Result:
Auto-scroll is not working.
In my case, I open an immersiveSpace and windowGroupA together. When I successfully push a new windowGroupB from windowGroupA, dismissing windowGroupB should return me to windowGroupA. However, this fails, and windowGroupA remains in the background scenePhase. I tried closing immersiveSpace, and it worked successfully. Therefore, pushWindow cannot be used when immersiveSpace is open.
Hi, i am currently updating my app in SwiftUI from iOS 16.4 to 18.0, i am getting in xcode these new warning
@State' used inline will not work unless tagged with '@Previewable'
so i fix the problem with the suggestions and add the new tag @Previewable and put the variable in the first line of the preview
#Preview {
@Previewable @State var enabled: Bool = true
return NotificationLabel(enabled: $enabled, type: "test", icon: "star", title: "test", description: "test")
}
the problem is that my app is available from iOS 16.4 to iOS 18.0 and the preview gives me this error
'Previewable()' is only available in iOS 18.0 or newer
but if i put a versione if at the top i get another error
if #available(iOS 18.0, *){
@Previewable @State var enabled: Bool = true
@Previewable' items must be at root scope in the preview block
is there a way to silence the warning making a two version preview, one for iOS 18 and one for the previous versions?
I have a punycode link of the following type: https://xn--d1aqf.xn--p1ai/.However, clicking on this link, or opening it through the simulator, opens the page in the browser, not in the application. The system does not see that this domain is present in one of the applications, however, any other domain (example.com , for example), is validated by the system. What could this be related to?