Hi the below array and code to output a list item works fine:
var quotes = [
[
"quote": "I live you the more ...",
"order": "1"
],
[
"quote": "There is nothing permanent ...",
"order": "2"
],
[
"quote": "You cannot shake hands ...",
"order": "3"
],
[
"quote": "Lord, make me an instrument...",
"order": "4"
]
]
cell.textLabel?.text = quotes[indexPath.row]["quote"]
However if I change the "order" values to be numbers rather than text like below then for the above line I get an error message in Xcode "No exact matches in call to subscript". Please could someone tell me how to make it work with the numbers stored as numbers? (I'm wondering if creating an any array type and using the .text function has caused a conflict but I can't find how to resolve)
[
"quote": "I live you the more ...",
"order": 1
],
[
"quote": "There is nothing permanent ...",
"order": 2
],
[
"quote": "You cannot shake hands ...",
"order": 3
],
[
"quote": "Lord, make me an instrument...",
"order": 4
]
]
Thank you for any pointers :-)
Dive into the world of programming languages used for app development.
Post
Replies
Boosts
Views
Activity
I am using Xcode 15 and working on a localised app. I use the new String Catalogs feature which works great for my app. In my app I created some local package like Apple has done it in the Backyard Birds example. However the translations I did in the package's String Catalog won’t be used in the app. What am I doing wrong?
Hello Apple Team,
I'm trying to import the Audodesk FBX SDK to my Objective-C iOS Project.
The SDK is written in C++, but has support for iOS and the iOS simulator architectures.
I've added the path to the include folder in the Header Search Path
I've also added the paths to libfbxsdk.a in the Library Search Paths
Finally, I've added the libfbxsdk.a file to the Link Binary with Libraries.
However, when I build the project, I get the following error:
building for 'iOS', but linking in object file (/Users/Lond/Documents/v2/Autodesk/iOS/2020.3.7/lib/ios/debug/libfbxsdk.a[28](fbxalloc.cxx.o)) built for 'macOS'
In the terminal, if I type the command:
lipo -info libfbxsdk.a
I get the message
Non-fat file: libfbxsdk.a is architecture: arm64
confirming that I'm using the library for the correct architecture.
Do I need to add any other confifuration option? (Like the other linker flag or something else)
I'm quite new to C++, and integrating a C++ SDK into iOS is not easy.
I'm using Mac Os Sonoma 14.6.1
Tested on Xcode 15.4 and 16.2
Target Device: iPhone 13 Pro (iOS 17.6.1)
iOS FBX SDK version: 2020.3.7
Link to the SDK if needed:
https://aps.autodesk.com/developer/overview/fbx-sdk
Any help would be greatly appreciated
Thank you
The following code works when compiling for macOS:
print(NSMutableDictionary().isEqual(to: NSMutableDictionary()))
but produces a compiler error when compiling for iOS:
'NSMutableDictionary' is not convertible to '[AnyHashable : Any]'
NSDictionary.isEqual(to:) has the same signature on macOS and iOS. Why does this happen? Can I use NSDictionary.isEqual(_:) instead?
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?
On iOS 18 some string functions return incorrect values in some cases.
Found problems on replacingOccurrences() and split() functions, but there may be others.
In the results of these functions in some cases a character is left in the result string when it shouldn't.
This did not happen on iOS17 and older versions.
I created a very simple Test Project to reproduce the problem.
If I run these tests on iOS17 or older the tests succeed.
If I run these tests on iOS18 the tests fail.
test_TestStr1() function shows a problem in replacingOccurrences() directly using strings.
test_TestStr2() function shows a problem in split() that seems to happen only when bridging from NSString to String.
import XCTest
final class TestStrings18Tests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func test_TestStr1()
{
let str1 = "_%\u{7}1\u{7}_";
let str2 = "%\u{7}1\u{7}";
let str3 = "X";
let str4 = str1.replacingOccurrences(of: str2, with: str3);
//This should be true
XCTAssertTrue(str4 == "_X_");
}
func test_TestStr2()
{
let s1 = "TVAR(6)\u{11}201\"Ã\"\u{11}201\"A\"";
let s2 = s1.components(separatedBy: "\u{11}201");
let t1 = NSString("TVAR(6)\u{11}201\"Ã\"\u{11}201\"A\"") as String;
let t2 = t1.components(separatedBy: "\u{11}201");
XCTAssertTrue(s2.count == t2.count);
let c = s2.count
//This should be True
XCTAssertTrue(s2[0] == t2[0]);
}
}
Recently I updated to Xcode 14.0. I am building an iOS app to convert recorded audio into text. I got an exception while testing the application from the simulator(iOS 16.0).
[SpeechFramework] -[SFSpeechRecognitionTask handleSpeechRecognitionDidFailWithError:]_block_invoke Ignoring subsequent recongition error: Error Domain=kAFAssistantErrorDomain Code=1101 "(null)"
Error Domain=kAFAssistantErrorDomain Code=1107 "(null)"
I have to know what does the error code means and why this error occurred.
Does anyone know if there will be a Swift 6 version of "The Swift Programming Language" book and if so, when it will be released for Apple Books?
Hi I'm new here - I'm trying to learn Swift and SwiftUI.
Tried on PluralSight and Udemy but they have been outdated and thus hard to follow.
So after finding Apples own guides I felt relieved and happy, but now I'm stuck again.
After they've updated Xcode to use #Preview instead of PreviewProvider it's hard to follow along on their tutorial.
Does anyone know of good resources to study SwiftUI? Or know if apple plan to update their tutorials any time soon?
I'm here now if anyone's interested or it's useful information: https://developer.apple.com/tutorials/app-dev-training/managing-state-and-life-cycle
Hello everyone,
There is one thing about Objective-C's memory management that confuses me, which is a returned object's lifetime from methods with names doesn't start with "alloc", "new", "copy", or "mutableCopy".
Take this as an example, when using NSBitmapImageRep's representationUsingType:properties: method, it returns an NSData object (reference: https://developer.apple.com/documentation/appkit/nsbitmapimagerep/representation(using:properties:)?language=objc).
While testing this out, the NSData seemed to be an owned object (it doesn't get released until the end of the program).
From what I understand, this may be an auto-released object which is released at the end of an autorelease pool block.
Could someone explain this in more detail? What if I want to release that NSData object before the end of the autorelease pool block? How can I know which object is autoreleased, borrowed, or owned?
I've created a Julia interface for Apple Accelerate's libSparse, via calling the library functions as if they were C (@ccall). I'm interested in using this in the context of power systems, where the sparse matrix is the Jacobian or the ABA matrix from a sparse grid network. However, I'm puzzled by the performance.
I ran a sampling profiler on repeated in-place solves of Ax = b for a large sparse matrix A and random dense vectors b. (A is size 30k, positive definite so Cholesky factorization.) The 2 functions with the largest impact are _SparseConvertFromCoordinate_Double from libSparse.dylib, and BLASStateRelease from libBLAS.dylib. That strikes me as bizarre. This is an in-place solve: there should be minimal overheard from allocating/deallocating memory. Also, it seems strange that the library would repeatedly convert from coordinate form. Is this expected behavior?
Thinking it might be an artifact of the Julia-C interface, I wrote up a similar program in C/Objective-C. I didn't profile it, but timing the same operation (repeated in-place solves of Ax = b for random vectors b, with the same matrix A as in the Julia) gave the same duration. I've attached the C/Objective-C below.profiling-comparison.m.txt
If you're familiar with Julia, the following will give you the matrix I was working with:
using PowerSystems, PowerNetworkMatrices
sys = System("pglib_opf_case30000_goc.m")
A = PowerNetworkMatrices.ABA_Matrix(sys).data
where you can find the .m file here. (As a crude way to transfer A from Julia to C, I wrote the 3 arrays A.nzval, A.colptr, and A.rowval to .txt files as space-separated lists of numbers: the above C/objective-C reads in those files.) To duplicate my Julia profiling, do pkg> add AppleAccelerate#libSparse Profile--note the #libSparse part, these features aren't on the main branch--then run
using AppleAccelerate, Profile
# run previous code snippet to define A
M, N = 10000, size(A)[1]
bs = [rand(N) for _ in 1:M]
aa_fact = AAFactorization(A)
factor!(aa_fact)
solve!(aa_fact, bs[1]) # pre-compile before we profile.
Profile.init(n = 10^6, delay = 0.0003)
@profile (for i in 1:M; solve!(aa_fact, bs[i]); end;)
Profile.print(C = true, format = :flat, sortedby = :count)
I've got a watch app, still with storyboard, WKInterfaceController and WatchConnectivity.
After updating it for swift 6 concurrency I thought I'd keep it for a little while without swift 6 concurrency dynamic runtime check.
So I added -disable-dynamic-actor-isolation in OTHER_SWIFT_FLAGS, but it doesn't seem to have an effect for the Apple Watch target. Without manually marking callbacks where needed with @Sendable in dynamic checks seem to be in place.
swiftc invocation is as (includes -disable-dynamic-actor-isolation):
swiftc -module-name GeoCameraWatchApp -Onone -enforce-exclusivity\=checked ... GeoCameraWatchApp.SwiftFileList -DDEBUG -enable-bridging-pch -disable-dynamic-actor-isolation -D DEBUG -enable-experimental-feature DebugDescriptionMacro -sdk /Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform/Developer/SDKs/WatchOS11.2.sdk -target arm64_32-apple-watchos7.0 -g -module-cache-path /Users/stand/Library/Developer/Xcode/DerivedData/ModuleCache.noindex -Xfrontend -serialize-debugging-options -enable-testing -index-store-path /Users/stand/Library/Developer/Xcode/DerivedData/speedo-almhjmryctkitceaufvkvhkkfvdw/Index.noindex/DataStore -enable-experimental-feature OpaqueTypeErasure -Xcc -D_LIBCPP_HARDENING_MODE\=_LIBCPP_HARDENING_MODE_DEBUG -swift-version 6
...
-disable-dynamic-actor-isolation flag seems to be working for the iOS targets, I believe.
The flag is described here
Am I missing something? Should the flag work for both iOS and Apple Watch targets?
decidePolicyFor delegate method:
import WebKit
@objc extension DocumentationVC
{
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
Being called just alright in swift 5 minimal concurrency.
Raising concurrency to complete with swift 5 or swift 6. Changing the code to avoid warnings:
@preconcurrency import WebKit
@objc extension DocumentationVC
{
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
The delegate method is not being called. Changing back to swift 5 concurrency minimal - it is called.
Looking at WKNavigationDelegate:
WK_SWIFT_UI_ACTOR
@protocol WKNavigationDelegate <NSObject>
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(WK_SWIFT_UI_ACTOR void (^)(WKNavigationActionPolicy))decisionHandler WK_SWIFT_ASYNC(3);
Changing the delegate method to:
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void) {
And it is called across swift 5 concurrency minimal to complete to swift 6.
I thought, the meaning of @preconcurrency import WebKit was to keep the delegate without @MainActor before the (WKNavigationActionPolicy) still matching regardless the swift concurrency mode?
My point is - this can introduce hidden breaking changes? I didn't see this documented anyhow at: https://www.swift.org/migration/documentation/migrationguide/.
decidePolicyFor is an optional method - so if signature 'mismatches' - there will be no warning on not-implementing the delegate method.
How do we catch or diagnose irregularities like this? Is it something @preconcurrency import WebKit should be ensuring and it is not?
Is this delegate mismatch a bug on swift side or something we should be taking care of while migrating? If it is on us, how do we diagnose these potential mismatches?
Hi!
We are seeing a bit surprising behavior of dispatch_main on macOS where it seems to spawn a different thread instead of preserving the one it gets called from.
Managed to reproduce it in a completely empty command-line tool project in Xcode
int main(int argc, const char * argv[]) {
@autoreleasepool {
dispatch_main();
return 0;
}
}
I put a breakpoint on the line with dispatch_main and see that I am on Thread 1 and inside main function. That makes sense.
I resume execution and pause again. Looking at Thread output in Xcode, I can only see Thread 2.
Thread 1 is gone and the executable keeps on running.
So dispatch_main did what was expected (prevented the process from termination) but throws out the thread it was called from and creates a new one? Is that behavior expected or am I missing something?
Just a brain teaser at this point. But we could not make sense out of it. :)
Hey all!
During the migration of a production app to swift 6, I've encountered a problem: when hitting the UNUserNotificationCenter.current().requestAuthorization the app crashes.
If I switch back to Language Version 5 the app works as expected.
The offending code is defined here
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
FirebaseConfiguration.shared.setLoggerLevel(.min)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { _, _ in }
application.registerForRemoteNotifications()
Messaging.messaging().delegate = self
return true
}
}
The error is depicted here:
I have no idea how to fix this.
Any help will be really appreciated
thanks in advance
I have a simple shell script as follows:
#!/bin/bash
OUTPUT="network.$(date +'%d-%m-%y').info.txt"
SUPPORT_ID="emailaddress"
echo "---------------------------------------------------" > $OUTPUT
echo "Run date and time: $(date)" >> $OUTPUT
echo "---------------------------------------------------" >> $OUTPUT
ifconfig >> $OUTPUT
echo "---------------------------------------------------" >> $OUTPUT
echo "Network info written to file: $OUTPUT."
echo "Please email this file to: $SUPPORT_ID."
It just dumps the network config into a file. At some point I will have the file emailed out, but right now I'm just trying to figure out why the output looks like the following?
bash ./test.sh
.etwork info written to file: network.26-01-25.info.txt
.lease email this file to: emailaddress
Why in the world does the initial character of the last couple of "echo" commands get clipped and turned into periods? The echos for the output of the commands piped into the output file are fine. Strange...
Any ideas?
I have a simple shell script as follows:
#!/bin/bash
OUTPUT="network.$(date +'%d-%m-%y').info.txt"
SUPPORT_ID="email"
echo "---------------------------------------------------" > $OUTPUT
echo "Run date and time: $(date)" >> $OUTPUT
echo "---------------------------------------------------" >> $OUTPUT
ifconfig >> $OUTPUT
echo "---------------------------------------------------" >> $OUTPUT
echo "Network info written to file: $OUTPUT."
echo "Please email this file to: $SUPPORT_ID."
It just dumps the network config into a file. At some point I will have the file emailed out, but right now I'm just trying to figure out why the output looks like the following?
bash ./test.sh
.etwork info written to file: network.26-01-25.info.txt
.lease email this file to: email
Why in the world does the initial character of the last couple of "echo" commands get clipped and turned into periods? The echos for the output of the commands piped into the output file are fine. Strange...
Any ideas?
I have a class that I want to custom encode into JSON:
class Declination: Decodable, Encodable {
var asString: String
var asDouble: Double
init(_ asString: String) {
self.asString = asString
self.asDouble = raToDouble(asString)
}
required init(from decoder: Decoder) throws {
let value = try decoder.singleValueContainer()
self.asString = try value.decode(String.self)
self.asDouble = declinationToDouble(asString)
}
}
As you can see, I calculate the double form of the declination when I decode a JSON file containing the data. What I want to do now is ENCODE the class back out as a single string.
Currently the standard JSON encode in Swift produces the following:
"declination":{"asDouble":18.26388888888889,"asString":"+18:15:50.00"}
what I want to produce is:
declination:"+18:15:50.00"
How can I easily do that? I've read up about custom encoders and such, and I get confused about the containers and what keys are being used. I think there might be a simple answer where I could just code:
extension Coordinate: Encodable {
func encode(to encoder: Encoder) throws {
return encoder.encode(self.asString)
}
}
But experienced Swift developers will immediately see that won't work. Should I do JSONSerialization instead? Can I just write a toString() extension and have JSON pick that up?
Any help would be appreciated.
Thanks,
Robert
I’m working on a project in Xcode 16.2 and encountered an issue where getAPI() with a default implementation in a protocol extension doesn’t show up in autocomplete. Here’s a simplified version of the code:
import Foundation
public protocol Repository {
func getAPI(from url: String?)
}
extension Repository {
public func getAPI(from url: String? = "https://...") {
getAPI(from: url)
}
}
final class _Repository: Repository {
func getAPI(from url: String?) {
// Task...
}
}
let repo: Repository = _Repository()
repo.getAPI( // Autocomplete doesn't suggest getAPI()
I’ve tried the following without success:
• Clean build folder
• Restart Xcode
• Reindexing
Is there something wrong with the code, or is this a known issue with Xcode 16.2? I’d appreciate any insights or suggestions.
Hello, I have an issue with importing some .mp3 files into a swift playground project (in Xcode, not in the Playground app). They worked fine in the Xcode project, but for some reason playgrounds isn't able to find them. I imported them the exact same way as I did in the Xcode project.