For my app I was trying to write some tests to ensure the functionality of all features. As I am using Xcode 16.0 I thought I might use Swift testing which was newly introduced and replaces XCTest.
I created a new test target with Swift Testing and tried to run the first test, which was created automatically by the system.
struct FinancialTests {
@Test func testExample() async throws {
#expect(true)
}
}
Xcode is also showing the test diamond next to the function so I clicked on it to execute it. The app started to build and the build ended successfully. The the next step was testing. And after waiting for 10 minutes or so, no test was executed. First I thought maybe the test was not found, but in the test case overview all tests were shown:
The run only shows this:
Can someone help me to get this running.
Many thanks!
Dive into the world of programming languages used for app development.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
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?
Topic:
Programming Languages
SubTopic:
General
I have a simple wrapper class around WCSession to allow for easier unit testing. I'm trying to update it to Swift 6 concurrency standards, but running into some issues. One of them is in the sendMessage function (docs here
It takes [String: Any] as a param, and returns them as the reply. Here's my code that calls this:
@discardableResult
public func sendMessage(_ message: [String: Any]) async throws -> [String: Any] {
return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<[String: Any], Error>) in
wcSession.sendMessage(message) { response in
continuation.resume(returning: response) // ERROR HERE
} errorHandler: { error in
continuation.resume(throwing: error)
}
}
}
However, I get this error:
Sending 'response' risks causing data races; this is an error in the Swift 6 language mode
Which I think is because Any is not Sendable. I tried casting [String: Any] to [String: any Sendable] but then it says:
Conditional cast from '[String : Any]' to '[String : any Sendable]' always succeeds
Any ideas on how to get this to work?
Hello together,
since Xcode Version > 15 the following error handling causes following error "Pattern of type 'DecodingError' cannot match 'Never'
func getSupportedCountries() async {
// fetch all documents from collection "seasons" from firestore
let queryCountries = try? await db.collection("countries").getDocuments()
if queryCountries != nil {
self.countries = (queryCountries!.documents.compactMap({ (queryDocumentSnapshot) -> Country? in
let result = Result { try? queryDocumentSnapshot.data(as: Country.self) }
switch result {
case .success(let country):
if let country = country {
// A country value was successfully initialized from the DocumentSnapshot
self.errorMessage = nil
return country
}
else {
// A nil value was successfully initialized from the DocumentSnapshot,
// or the DocumentSnapshot was nil
self.errorMessage = "Document doesn't exist."
return nil
}
case .failure(let error):
// A Country value could not be initialized from the DocumentSnapshot
switch error {
case DecodingError.typeMismatch(_, let context):
self.errorMessage = "\(error.localizedDescription): \(context.debugDescription)"
case DecodingError.valueNotFound(_, let context):
self.errorMessage = "\(error.localizedDescription): \(context.debugDescription)"
case DecodingError.keyNotFound(_, let context):
self.errorMessage = "\(error.localizedDescription): \(context.debugDescription)"
case DecodingError.dataCorrupted(let key):
self.errorMessage = "\(error.localizedDescription): \(key)"
default:
self.errorMessage = "Error decoding document: \(error.localizedDescription)"
}
return nil
}
}))
} else {
self.errorMessage = "No documents in 'countries' collection"
return
}
}
the interesting part of the code where XCODE shows an error is from "switch error" downwards.
Does anyone of you have an idea what's wrong?
Ay help appreciated !
Thx, Peter
Hello,
I was expecting the code below to print the test message "line 25" because the class "API" is being called on line 57. But "line 25" is not being displayed in the debug window, please could you tell me why?
This is the debugging window:
line 93
0
line 93
0
line 93
0
import UIKit
// not sure these 2 below are needed
import SwiftUI
import Combine
struct NewsFeed: Codable {
var id: String
var name: String
var country: String
var type: String
var situation: String
var timestamp: String
}
let urlString = "https://www.notafunnyname.com/jsonmockup.php"
let url = URL(string: urlString)
let session = URLSession.shared
class API: ObservableObject {
let dataTask = session.dataTask(with: url!) { (data, response, error) in
print("line 25")
var dataString = String(data: data!, encoding: String.Encoding.utf8)
if error == nil && data != nil {
// Parse JSON
let decoder = JSONDecoder()
do {
var newsFeed = try decoder.decode([NewsFeed].self, from: data!)
print("line 38")
// print(newsFeed)
// print("line 125")
// print(newsFeed.count)
print(error)
}
catch{
print("Line 46, Error in JSON parsing")
print(error)
}
}
}.resume
// Make the API Call - not sure why but error clears if moved to line above
// dataTask.resume()
}
let myAPIarray = API()
class QuoteTableViewController: UITableViewController {
var newsFeed: [[String: String]] = []
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// let selectedQuote = quotes[indexPath.row]
// performSegue(withIdentifier: "moveToQuoteDetail", sender: selectedQuote)
}
override func viewDidLoad() {
super.viewDidLoad()
// tableView.dataSource = self
}
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// (viewDidLoad loads after tableView)
// #warning Incomplete implementation, return the number of rows
print("line 93")
print(newsFeed.count)
return 10
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
let cell = UITableViewCell ()
cell.textLabel?.text = "test"
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
// getPrice()
print("test_segue")
if let quoteViewController = segue.destination as? QuoteDetailViewController{
if let selectedQuote = sender as? String {
quoteViewController.title = selectedQuote
}
}
}
}
Topic:
Programming Languages
SubTopic:
Swift
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?
Topic:
Programming Languages
SubTopic:
Swift
I am using swiftui lately in my iOS mobile app, The Mobile app already has a pipeline that detect any experimental features and throw an error
I am using swift 5 and as you all know SwiftUI is using some of OpaqueTypeErasure utility types like "some"
I heard that in swift 6 the OpaqueTypeErasure is not experimental anymore
But upgrading the app swift version will be a very long process
Also changing the pipeline will be a very long and tiring process
So i want to know if there is a way to remove OpaqueTypeErasure from SwiftUI and what is the alternatives for bypassing the error that being thrown from the pipeline
"the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions" ...... it killing me !!!!
Hi, I have issue on build my react native project and got this error "Undefined symbol: _swift_willThrowTypedImpl" how can I fix it?
I filed the following issue on swiftlang/swift on GitHub (Aug 8th), and a followup the swift.org forums, but not getting any replies. As we near the release of Swift 6.2, I want to know if what I'm seeing below is expected, or if it's another case where the compiler needs a fix.
protocol P1: Equatable { }
struct S1: P1 { }
// Error: Conformance of 'S1' to protocol 'P1' crosses into main actor-isolated code an can cause data races
struct S1Workaround: @MainActor P1 { } // OK
// Another potential workaround if `Equatable` conformance can be moved to the conforming type.
protocol P2 { }
struct S2: Equatable, P2 { } // OK
There was a prior compiler bug fix which addressed inhereted protocols regarding @MainActor. For Equatable, one still has to use @MainActoreven when the default actor isolation is MainActor.
Also affects Hashable and any other protocol inheriting from Equatable.
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.
I have a Swift Package that contains an Objective-C target. The target contains Objective-C literals but unfortunately the compiler says "Initializer element is not a compile-time constant", what am I doing wrong?
Based on the error triggering in the upper half, I take it that objc_array_literals is on.
My target definition looks like:
.target(
name: "MyTarget",
path: "Sources/MySourcesObjC",
publicHeadersPath: "include",
cxxSettings: [
.unsafeFlags("-fobjc-constant-literals")
]
),
I believe Objective-C literals are enabled since a long time but I still tried passing in the -fobjc-constant-literals flag and no luck.
To be clear I'm not interested in a run-time initialization, I really want it to be compile time. Does anyone know what I can do?
Hello,
I have a test variable here which works fine:
var quotes: [(quote: String, order: Int)] = [
("I live you the more ...", 1),
("There is nothing permanent ...", 2),
("You cannot shake hands ...", 3),
("Lord, make me an instrument...", 4)
]
and I have a test function which successfully pulls data from a mysql database via a web service and displays it via the "print" function:
func getPrice(){
if let url = URL(string:"https://www.TEST.com/test_connection.php"){
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let data = data{
if let json = try? JSONDecoder().decode([[String:String]].self, from: data){
json.forEach { row in
print(row["quote"]!)
print(row["order"]!)
}
}
else{
}
}
else{
print("wrong :-(")
}
}.resume()
}
}
Please can you tell me how to re-write the quotes variable/array so that it returns the results that are found in the getPrice() function?
Topic:
Programming Languages
SubTopic:
Swift
I'm using xcode 16.1 withSwift. I want to know how to call a function passing in an array. Also I need to know how to declare the function receiving the array. I currently have:
func myfunc(costa: [Double]) {
}
I call it like this:
myfunc(costa:[ ])
It's an array of Doubles. I don't get any errors but the array is always empty. Please help. Thank you.
Topic:
Programming Languages
SubTopic:
Swift
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?
Hello,
This test code for creating an array using a loop works:
var quotes: [(id: String, name: String)] {
var output: [(id: String, name: String)] = []
for i in 1...numberOfRows {
let item: (id: String, name: String) = ("\(i)", "Name \(i)")
output.append(item)
}
return output
}
But if I try to apply this logic to retrieving data from a web service using the below code I am getting 2 errors:
For the line “quotes.append(item)” I am getting the error message “Cannot use mutating member on immutable value: ‘quotes’ is a get-only property."
For the line “return output” I am getting the error message “Cannot find ‘output’ in scope."
if let url = URL(string:"https://www.TEST.com/test_connection.php"){
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let data = data{
if let json = try? JSONDecoder().decode([[String:String]].self, from: data){
json.forEach { row in
var item: (id: String, name: String) = ("test id value", "test name value")
quotes.append(item)
}
return output
}
}
}
}
Topic:
Programming Languages
SubTopic:
Swift
I’m aware that Xcode version 26 beta 3 provides an option to enable Swift’s Approachable Concurrency feature at the project level. However, I’d like to achieve the same for a Swift Package. Could you please advise on how to enable Approachable Concurrency support specifically for a Swift Package?
In my code I use a binding that use 2 methods to get and get a value. There is no problem with swift 5 but when I swift to swift 6 the compiler fails :
Here a sample example of code to reproduce the problem :
`import SwiftUI
struct ContentView: View {
@State private var isOn = false
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
Toggle("change it", isOn: Binding(get: getValue, set: setValue(_:)))
}
.padding()
}
private func getValue() -> Bool {
isOn
}
private func setValue(_ value: Bool) {
isOn = value
}
}`
Xcode compiler log error :
1. Apple Swift version 6.1.2 (swiftlang-6.1.2.1.2 clang-1700.0.13.5) 2. Compiling with the current language version 3. While evaluating request IRGenRequest(IR Generation for file "/Users/xavierrouet/Developer/TestCompilBindingSwift6/TestCompilBindingSwift6/ContentView.swift") 4. While emitting IR SIL function "@$sSbScA_pSgIeAghyg_SbIeAghn_TR". for <<debugloc at "<compiler-generated>":0:0>>Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var LLVM_SYMBOLIZER_PATH` to point to it):
0 swift-frontend 0x000000010910ae24 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) + 56
1 swift-frontend 0x0000000109108c5c llvm::sys::RunSignalHandlers() + 112
2 swift-frontend 0x000000010910b460 SignalHandler(int) + 360
3 libsystem_platform.dylib 0x0000000188e60624 _sigtramp + 56
4 libsystem_pthread.dylib 0x0000000188e2688c pthread_kill + 296
5 libsystem_c.dylib 0x0000000188d2fc60 abort + 124
6 swift-frontend 0x00000001032ff9a8 swift::DiagnosticHelper::~DiagnosticHelper() + 0
7 swift-frontend 0x000000010907a878 llvm::report_fatal_error(llvm::Twine const&, bool) + 280
8 swift-frontend 0x00000001090aef6c report_at_maximum_capacity(unsigned long) + 0
9 swift-frontend 0x00000001090aec7c llvm::SmallVectorBase::grow_pod(void*, unsigned long, unsigned long) + 384
10 swift-frontend 0x000000010339c418 (anonymous namespace)::SyncCallEmission::setArgs(swift::irgen::Explosion&, bool, swift::irgen::WitnessMetadata*) + 892
11 swift-frontend 0x00000001035f8104 (anonymous namespace)::IRGenSILFunction::visitFullApplySite(swift::FullApplySite) + 4792
12 swift-frontend 0x00000001035c876c (anonymous namespace)::IRGenSILFunction::visitSILBasicBlock(swift::SILBasicBlock*) + 2636
13 swift-frontend 0x00000001035c6614 (anonymous namespace)::IRGenSILFunction::emitSILFunction() + 15860
14 swift-frontend 0x00000001035c2368 swift::irgen::IRGenModule::emitSILFunction(swift::SILFunction*) + 2788
15 swift-frontend 0x00000001033e7c1c swift::irgen::IRGenerator::emitLazyDefinitions() + 5288
16 swift-frontend 0x0000000103573d6c swift::IRGenRequest::evaluate(swift::Evaluator&, swift::IRGenDescriptor) const + 4528
17 swift-frontend 0x00000001035c15c4 swift::SimpleRequest<swift::IRGenRequest, swift::GeneratedModule (swift::IRGenDescriptor), (swift::RequestFlags)17>::evaluateRequest(swift::IRGenRequest const&, swift::Evaluator&) + 180
18 swift-frontend 0x000000010357d1b0 swift::IRGenRequest::OutputType swift::Evaluator::getResultUncached<swift::IRGenRequest, swift::IRGenRequest::OutputType swift::evaluateOrFatalswift::IRGenRequest(swift::Evaluator&, swift::IRGenRequest)::'lambda'()>(swift::IRGenRequest const&, swift::IRGenRequest::OutputType swift::evaluateOrFatalswift::IRGenRequest(swift::Evaluator&, swift::IRGenRequest)::'lambda'()) + 812
19 swift-frontend 0x0000000103576910 swift::performIRGeneration(swift::FileUnit*, swift::IRGenOptions const&, swift::TBDGenOptions const&, std::__1::unique_ptr<swift::SILModule, std::__1::default_deleteswift::SILModule>, llvm::StringRef, swift::PrimarySpecificPaths const&, llvm::StringRef, llvm::GlobalVariable**) + 176
20 swift-frontend 0x0000000102f61af0 generateIR(swift::IRGenOptions const&, swift::TBDGenOptions const&, std::__1::unique_ptr<swift::SILModule, std::__1::default_deleteswift::SILModule>, swift::PrimarySpecificPaths const&, llvm::StringRef, llvm::PointerUnion<swift::ModuleDecl*, swift::SourceFile*>, llvm::GlobalVariable*&, llvm::ArrayRef<std::__1::basic_string<char, std::__1::char_traits, std::__1::allocator>>) + 156
21 swift-frontend 0x0000000102f5d07c performCompileStepsPostSILGen(swift::CompilerInstance&, std::__1::unique_ptr<swift::SILModule, std::__1::default_deleteswift::SILModule>, llvm::PointerUnion<swift::ModuleDecl*, swift::SourceFile*>, swift::PrimarySpecificPaths const&, int&, swift::FrontendObserver*) + 2108
22 swift-frontend 0x0000000102f5c0a8 swift::performCompileStepsPostSema(swift::CompilerInstance&, int&, swift::FrontendObserver*) + 1036
23 swift-frontend 0x0000000102f5f654 performCompile(swift::CompilerInstance&, int&, swift::FrontendObserver*) + 1764
24 swift-frontend 0x0000000102f5dfd8 swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) + 3716
25 swift-frontend 0x0000000102ee20bc swift::mainEntry(int, char const**) + 5428
26 dyld 0x0000000188a86b98 start + 6076
Using Xcode 16.4 / Mac OS 16.4
I'm developing an audio unit for use on iOS. The AUv3 worked fine with xcode 15.X and swift 5.X. I recently tried to submit an update to my plug-in but Apple refused submission because my Xcode was not the latest. Now that I'm on Xcode 16.4 I can't get my project to compile, even when following all of the same previous steps.
As one example of a change, Xcode doesn't appear to include the “C++ and Objective-C interoperability” build setting that it used to. This setting is noted in the Swift documentation and I used to need it, https://www.swift.org/documentation/cxx-interop/project-build-setup/#mixing-swift-and-c-using-xcode
Currently my C++ code can't see anything from Swift, and I get a "Use of undeclared identifier 'project_name'". I've selected Switch support for version 5.0 in an attempt to minimize changes from Apple.
My process is I generate an Xcode project file from my audio plugin support, JUCE. Then I add in the swift files, click yes to create bridging headers, but c++ doesn't see swift anymore. I'd greatly appreciate any suggestions.
Topic:
Programming Languages
SubTopic:
Swift
At least with macOS Sequoia 15.5 and Xcode 16.3:
$ cat test.cc
#include &lt;locale.h&gt;
#include &lt;string.h&gt;
#include &lt;xlocale.h&gt;
int main(void) {
locale_t l = newlocale(LC_ALL_MASK, "el_GR.UTF-8", 0);
strxfrm_l(NULL, "ό", 0, l);
return 0;
}
$ c99 test.c &amp;&amp; ./a.out
Assertion failed: (p-&gt;val == key), function lookup_substsearch, file collate.c, line 596.
Abort trap: 6