Is there a swift6 manual that will teach me how to code in swift?
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Is it ok for an Actor type to have a Publisher as a property to let others observe changes over time? Or use the @Published property wrapper to achieve this?
actor MyActor {
var publisher = PassthroughSubject<Int, Never>()
var data: Int {
didSet {
publisher.send(data)
}
}
...
}
// Usage
var tasks = Set<AnyCancellable>()
let actor = MyActor()
Task {
let publisher = await actor.publisher
publisher.sink { print($0) }.store(in: &tasks)
}
This seems like this should be acceptable. I would expect a Publisher to be thread safe, and as long as the Output is a value type things should be fine.
I have been getting random EXC_BAD_ACCESS errors when using this approach. But turning on the address sanitizer causes these crashes to go away. I know that isn't very specific but I wanted to start by seeing if this type of pattern is ok to do.
We are getting a crash _dispatch_assert_queue_fail when the cancellationHandler on NSProgress is called.
We do not see this with iOS 17.x, only on iOS 18. We are building in Swift 6 language mode and do not have any compiler warnings.
We have a type whose init looks something like this:
init(
request: URLRequest,
destinationURL: URL,
session: URLSession
) {
progress = Progress()
progress.kind = .file
progress.fileOperationKind = .downloading
progress.fileURL = destinationURL
progress.pausingHandler = { [weak self] in
self?.setIsPaused(true)
}
progress.resumingHandler = { [weak self] in
self?.setIsPaused(false)
}
progress.cancellationHandler = { [weak self] in
self?.cancel()
}
When the progress is cancelled, and the cancellation handler is invoked. We get the crash. The crash is not reproducible 100% of the time, but it happens significantly often. Especially after cleaning and rebuilding and running our tests.
* thread #4, queue = 'com.apple.root.default-qos', stop reason = EXC_BREAKPOINT (code=1, subcode=0x18017b0e8)
* frame #0: 0x000000018017b0e8 libdispatch.dylib`_dispatch_assert_queue_fail + 116
frame #1: 0x000000018017b074 libdispatch.dylib`dispatch_assert_queue + 188
frame #2: 0x00000002444c63e0 libswift_Concurrency.dylib`swift_task_isCurrentExecutorImpl(swift::SerialExecutorRef) + 284
frame #3: 0x000000010b80bd84 MyTests`closure #3 in MyController.init() at MyController.swift:0
frame #4: 0x000000010b80bb04 MyTests`thunk for @escaping @callee_guaranteed @Sendable () -> () at <compiler-generated>:0
frame #5: 0x00000001810276b0 Foundation`__20-[NSProgress cancel]_block_invoke_3 + 28
frame #6: 0x00000001801774ec libdispatch.dylib`_dispatch_call_block_and_release + 24
frame #7: 0x0000000180178de0 libdispatch.dylib`_dispatch_client_callout + 16
frame #8: 0x000000018018b7dc libdispatch.dylib`_dispatch_root_queue_drain + 1072
frame #9: 0x000000018018bf60 libdispatch.dylib`_dispatch_worker_thread2 + 232
frame #10: 0x00000001012a77d8 libsystem_pthread.dylib`_pthread_wqthread + 224
Any thoughts on why this is crashing and what we can do to work-around it? I have not been able to extract our code into a simple reproducible case yet. And I mostly see it when running our code in a testing environment (XCTest). Although I have been able to reproduce it running an app a few times, it's just less common.
I get many warnings like this when I build an old project.
I asked AI chatbot which gave me several solutions, the recommended one is:
var hashBag = [String: Int]()
func updateHashBag() async {
var tempHashBag = hashBag // make copy
await withTaskGroup(of: Void.self) { group in
group.addTask {
tempHashBag["key1"] = 1
}
group.addTask {
tempHashBag["key2"] = 2
}
}
hashBag = tempHashBag // copy back?
}
My understanding is that in the task group, the concurrency engine ensures synchronized modifications on the temp copy in multiple tasks. I should not worry about this.
My question is about performance.
What if I want to put a lot of data into the bag? Does the compiler do some kind of magics to optimize low level memory allocations? For example, the temp copy actually is not a real copy, it is a special reference to the original hash bag; it is only grammar glue that I am modifying the copy.
and yeah, swift vaguely is reminiscent of a programming language I developed, but
I want swift To do
return if (var blah:Int32 == 43){
blah = blah2;
}
your welcome !! thank me on my new accounting job lol =/
basically I want to return conditional statements for a private reason
I have a macro that converts expression into a string literal, e.g.:
#toString(variable) -> "variable"
#toString(TypeName) -> "TypeName"
#toString(\TypeName.property) -> "property"
In Xcode 16.3 #toString(TypeName) stopped to work, compilation throws 'Expected member name or initializer call after type name' error.
Everything works fine in Xcode 16.2. I tried to compare build settings between 16.2 and 16.3 but haven't noticed differences that may cause this new error.
The following works in both Xcode versions:
#toString(variable) -> "variable"
#toString(\TypeName.property) -> "property"
Seems like Xcode tries to compile code that shouldn't be compiled because of macro expansion.
Does anybody know what new has appeared in 16.3 and, perhaps, how to fix the problem?
Hi Apple Developer Community,
I'm facing a crash when updating an array of tuples from both a background thread and the main thread simultaneously. Here's a simplified version of the code in a macOS app using AppKit:
class ViewController: NSViewController {
var mainthreadButton = NSButton(title: "test", target: self, action: nil)
var numbers = Array(repeating: (dim: Int, key: String)(0, "default"), count: 1000)
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(mainthreadButton)
mainthreadButton.translatesAutoresizingMaskIntoConstraints = false
mainthreadButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
mainthreadButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
mainthreadButton.widthAnchor.constraint(equalToConstant: 100).isActive = true
mainthreadButton.heightAnchor.constraint(equalToConstant: 100).isActive = true
mainthreadButton.target = self
mainthreadButton.action = #selector(arraytest(_:))
}
@objc func arraytest(_ sender: NSButton) {
print("array update started")
// Background update
DispatchQueue.global().async {
for i in 0..<1000 {
self.numbers[i].dim = i
}
}
// Main thread update
var sum = 0
for i in 0..<1000 {
numbers[i].dim = i + 1
sum += numbers[i].dim
print("test \(sum)")
}
mainthreadButton.title = "test = \(sum)"
}
}
This results in a crash with the following message:
malloc: double free for ptr 0x136040c00
malloc: *** set a breakpoint in malloc_error_break to debug
What's interesting:
This crash only happens when the tuple contains a String ((dim: Int, key: String))
If I change the tuple type to use two Int values ((dim: Int, key: Int)), the crash does not occur
My Questions:
Why does mutating an array of tuples containing a String crash when accessed from multiple threads?
Why is the crash avoided when the tuple contains only primitive types like Int?
Is there an underlying memory management issue with value types containing reference types like String?
Any explanation about this behavior and best practices for thread-safe mutation of such arrays would be much appreciated.
Thanks in advance!
Hi, I'm trying to add Swift code to my Obj-C project. I've gone through all the tutorials and troubleshooting advice I can find online, no dice. I would appreciate any help, thank you so much in advance.
I add a new swift file to my Obj-C project
XCode offers to create a bridging header file for me, yes please
New .swift file and .h file are added to my project no problem
Header file shows up in build settings no problem
I add a new class to my new swift file ("@objc class HelloPrinter: NSObject")
When I build the app, nothing is generated in the bridging header file and the class is obviously inaccessible to my obj-c code
Is this supposed to work? My understanding is that it's supposed to work.
Somewhat concerning is the text that XCode puts in the bridging header file when it's created: "Use this file to import your target's public headers that you would like to expose to Swift."
I don't want to use this bridging header file for anything. I want XCode to GENERATE STUFF in the bridging file. I also don't want to expose anything to Swift. I want the opposite to happen. So I don't get this text at all. Thanks in advance again.
Topic:
Programming Languages
SubTopic:
Swift
I am a Chinese student beginner ,do you have any advice for me to learn swift?I don't know how to start it.Please!🙏
Topic:
Programming Languages
SubTopic:
Swift
Hi all,
I'm running into a Swift Concurrency issue and would appreciate some help understanding what's going on.
I have a protocol and an actor set up like this:
protocol PersistenceListener: AnyObject {
func persistenceDidUpdate(key: String, newValue: Any?)
}
actor Persistence {
func addListener(_ listener: PersistenceListener) {
listeners.add(listener)
}
/// Removes a listener.
func removeListener(_ listener: PersistenceListener) {
listeners.remove(listener)
}
// MARK: - Private Properties
private var listeners = NSHashTable<AnyObject>.weakObjects()
// MARK: - Private Methods
/// Notifies all registered listeners on the main actor.
private func notifyListeners(key: String, value: Any?) async {
let currentListeners = listeners.allObjects.compactMap { $0 as? PersistenceListener }
for listener in currentListeners {
await MainActor.run {
listener.persistenceDidUpdate(key: key, newValue: value)
}
}
}
}
When I compile this code, I get a concurrency error:
"Sending 'listener' risks causing data races"
I tried to build the project with Xcode 16.3 and I initially got an error that TARGET_IPHONE_SIMULATOR does not exist, then I changed this flag to TARGET_OS_SIMULATOR, but it did not solve the problem
I’m working with Swift and encountered an issue when using the contains method on an array. The following code works fine:
let result = ["hello", "world"].contains(Optional("hello")) // ✅ Works fine
However, when I try to use the same contains method with the array declared in a separate constant(or variable), I get a compile-time error:
let stringArray = ["hello", "world"]
let result = stringArray.contains(Optional("hello")) // ❌ Compile-time error
The compiler produces the following error message:
Cannot convert value of type 'Optional<String>' to expected argument type 'String'
Both examples seem conceptually similar, but the second one causes a compile-time error, while the first one works fine.
This confuses me because I know that Swift automatically promotes a non-optional value to an optional when comparing it with an optional value. This means "hello" should be implicitly converted to Optional("hello") for the comparison.
What I understand so far:
The contains(_:) method is defined as:
func contains(_ element: Element) -> Bool
Internally, it calls contains(where:), as seen in the Swift source code:
🔗 Reference
contains(where:) takes a closure that applies the == operator for comparison.
Since Swift allows comparing String and String? directly (String is implicitly promoted to String? when compared with an optional), I expected contains(where:) to work the same way.
My Questions:
Why does the first example work, but the second one fails with a compile-time error?
What exactly causes this error in the second case, even though both cases involve comparing an optional value with a non-optional value?
Does contains(_:) behave differently when used with an explicit array variable rather than a direct array literal? If so, why?
I know that there are different ways to resolve this, like using nil coalescing or optional binding, but what I’m really looking for is a detailed explanation of why this issue occurs at the compile-time level.
Can anyone explain the underlying reason for this behavior?
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
I’m working with Swift and ran into an issue when using the contains(_:) method on an array. The following code works fine:
let result = ["hello", "world"].contains(Optional("hello")) // ✅ Works fine
But when I try to use the same contains method with the array declared in a separate variable, I get a compile-time error:
let stringArray = ["hello", "world"]
let result = stringArray.contains(Optional("hello")) // ❌ Compile-time error
Both examples seem conceptually similar, but the second one causes a compile-time error, while the first one works fine.
I understand that when comparing an optional value (Optional("hello")) with a non-optional value ("hello"), Swift automatically promotes the non-optional value to an optional (i.e., "hello" becomes Optional("hello")).
🔗 reference
What I don’t understand is why the first code works but the second one doesn’t, even though both cases involve comparing an optional value with a non-optional value. I know that there are different ways to resolve this, like using nil coalescing or optional binding, but what I’m really looking for is a detailed explanation of why this issue occurs at the compile-time level.
Can anyone explain the underlying reason for this behavior?
I'm continuing with the migration towards Swift 6. Within one of our libraries, I want to check whether a parameter object: Any? confirms to Sendable.
I tried the most obvious one:
if let sendable = object as? Sendable {
}
But that results into the compiler error "Marker protocol 'Sendable' cannot be used in a conditional cast".
Is there an other way to do this?
Hello,
For the below code please can you tell me why the test code print("line 64") is being printed after the test code print("line 84") ? (i.e. how do I stop that happening?)
I would like the program to wait until the results array has been parsed before continuing the code (otherwise it does not have content to present).
I'm a bit confused why this is happening because I haven't written "async" anywhere.
import UIKit
struct NewsFeed: Codable {
var id: String
var name: String
var country: String
var type: String
var situation: String
var timestamp: String
}
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)
// try getting array results here
let urlString = "https://www.notafunnyname.com/jsonmockup.php"
let url = URL(string: urlString)
let session = URLSession.shared
let dataTask = session.dataTask(with: url!) { (data, response, error) in
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 64")
// print(newsFeed)
// print("line 125")
// print(newsFeed.count)
print(error)
}
catch{
print("Line 72, Error in JSON parsing")
print(error)
}
}
}
// Make the API Call
dataTask.resume()
// #warning Incomplete implementation, return the number of rows
print("line 84")
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
}
}
}
}
Many thanks
Topic:
Programming Languages
SubTopic:
Swift
Is there a way to achieve the following using C++/Swift interoperability:
class MyCppClass
{
public:
...
...
private:
bool member1;
ACppClass member2;
ASwiftClass member3;
}
I'm aware of the recent C++/Objective-C interoperability compiler setting, but can't find any information on whether this is possible.
I've watched the Apple video:
https://developer.apple.com/videos/play/wwdc2023/10172/
and seen this post from Quinn:
https://developer.apple.com/forums/thread/768928
but I don't see anyone discussing this kind of situation.
Thanks in advance.
Topic:
Programming Languages
SubTopic:
Swift
I ran into a problem, I have a recursive function in which Data type objects are temporarily created, because of this, the memory expands until the entire recursion ends. It would just be fixed using autoreleasepool, but it can't be used with async await, and I really don't want to rewrite the code for callbacks. Is there any option to use autoreleasepool with async await functions? (I Googled one option, that the Task already contains its own autoreleasepool, and if you do something like that, it should work, but it doesn't, the memory is still growing)
func autoreleasepool<Result>(_ perform: @escaping () async throws -> Result) async throws -> Result {
try await Task {
try await perform()
}.value
}
Hello,
Please see the test project at https://we.tl/t-aWAu7kk9lD
I have a json array showing in Xcode debugger (from the line "print(dataString)"):
Optional("[{\"id\":\"8e8tcssu4u2hn7a71tkveahjhn8xghqcfkwf1bzvtrw5nu0b89w\",\"name\":\"Test name 0\",\"country\":\"Test country 0\",\"type\":\"Test type 0\",\"situation\":\"Test situation 0\",\"timestamp\":\"1546848000\"},{\"id\":\"z69718a1a5z2y5czkwrhr1u37h7h768v05qr3pf1h4r4yrt5a68\",\"name\":\"Test name 1\",\"country\":\"Test country 1\",\"type\":\"Test type 1\",\"situation\":\"Test situation 1\",\"timestamp\":\"1741351615\"},{\"id\":\"fh974sv586nhyysbhg5nak444968h7hgcgh6yw0usbvcz9b0h69\",\"name\":\"Test name 2\",\"country\":\"Test country 2\",\"type\":\"Test type 2\",\"situation\":\"Test situation 2\",\"timestamp\":\"1741351603\"},{\"id\":\"347272052385993\",\"name\":\"Test name 3\",\"country\":\"Test country 3\",\"type\":\"Test type 3\",\"situation\":\"Test situation 3\",\"timestamp\":\"1741351557\"}]")
But my JSON decoder is throwing a catch error
Line 57, Error in JSON parsing
typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
This is the code:
let urlString = "https://www.notafunnyname.com/jsonmockup.php"
let url = URL(string: urlString)
guard url != nil else {
return
}
let session = URLSession.shared
let dataTask = session.dataTask(with: url!) { (data, response, error) in
var dataString = String(data: data!, encoding: String.Encoding.utf8)
print(dataString)
if error == nil && data != nil {
// Parse JSON
let decoder = JSONDecoder()
do {
let newsFeed = try decoder.decode(NewsFeed.self, from: data!)
print("line 51")
print(newsFeed)
print(error)
}
catch{
print("Line 57, Error in JSON parsing")
print(error)
}
}
}
// Make the API Call
dataTask.resume()
}
And this is my Codable file NewsFeed.swift:
struct NewsFeed: Codable {
var id: String
var name: String
var country: String
var type: String
var situation: String
var timestamp: String
}
Please do you know how to resolve the typeMismatch error?
Topic:
Programming Languages
SubTopic:
Swift
Hello,
I asked this question on 9th March but was asked to provide a project file and can't edit the original post. Please find the original question below and please find the new test project file at https://we.tl/t-fqAu8FrgUw.
I have a json array showing in Xcode debugger (from the line "print(dataString)"):
Optional("[{\"id\":\"8e8tcssu4u2hn7a71tkveahjhn8xghqcfkwf1bzvtrw5nu0b89w\",\"name\":\"Test name 0\",\"country\":\"Test country 0\",\"type\":\"Test type 0\",\"situation\":\"Test situation 0\",\"timestamp\":\"1546848000\"},{\"id\":\"z69718a1a5z2y5czkwrhr1u37h7h768v05qr3pf1h4r4yrt5a68\",\"name\":\"Test name 1\",\"country\":\"Test country 1\",\"type\":\"Test type 1\",\"situation\":\"Test situation 1\",\"timestamp\":\"1741351615\"},{\"id\":\"fh974sv586nhyysbhg5nak444968h7hgcgh6yw0usbvcz9b0h69\",\"name\":\"Test name 2\",\"country\":\"Test country 2\",\"type\":\"Test type 2\",\"situation\":\"Test situation 2\",\"timestamp\":\"1741351603\"},{\"id\":\"347272052385993\",\"name\":\"Test name 3\",\"country\":\"Test country 3\",\"type\":\"Test type 3\",\"situation\":\"Test situation 3\",\"timestamp\":\"1741351557\"}]")
But my JSON decoder is throwing the catch error "Error in JSON parsing"
This is the code:
let urlString = "https://www.notafunnyname.com/jsonmockup.php"
let url = URL(string: urlString)
guard url != nil else {
return
}
let session = URLSession.shared
let dataTask = session.dataTask(with: url!) { (data, response, error) in
var dataString = String(data: data!, encoding: String.Encoding.utf8)
print(dataString)
if error == nil && data != nil {
// Parse JSON
let decoder = JSONDecoder()
do {
let newsFeed = try decoder.decode(NewsFeed.self, from: data!)
print(newsFeed)
print(error)
}
catch{
print("Error in JSON parsing")
}
}
}
// Make the API Call
dataTask.resume()
}
And this is my Codable file NewsFeed.swift:
struct NewsFeed: Codable {
var id: String
var name: String
var country: String
var type: String
var overallrecsit: String
var dlastupd: String
var doverallrecsit: String
}
Please do you know why the parsing may be failing? Is it significant that in the debugging window the JSON is displaying backslashes before the quotation marks?
Thank you for any pointers :-)
Topic:
Programming Languages
SubTopic:
Swift