1,603
questions
0
votes
0
answers
59
views
Implement an efficient Encoder/Decoder [duplicate]
I am working on a binary Encoder/Decoder with the Codable protocol.
One of the goal is to be efficient. i.e. I would like to special case handling of Data/[UInt8] to minimize number of memory ...
-1
votes
1
answer
62
views
A better approach to decode same JSON with different structure in Swift? [closed]
I was dealing with a request that need to modify our iOS model structure, the modification was moving the EncodingOption parameter to the EditingOptions class from OutputOptions struct.
Hierarchy of ...
0
votes
2
answers
79
views
How to create an escape hatch in swift's Encodable
I'm looking for a way to create an escape hatch in Encodable. There are many JSON APIs that are more flexible than Encodable allows for. As an example, take the Anthropic API which allows you to ...
0
votes
0
answers
36
views
swift serialize [any Codable]
As part of a rewrite from a C++ codebase, I have a class with an array of any V, where V extends Codable. How can I create the required init and encode functions here?
import Foundation
protocol V: ...
2
votes
4
answers
119
views
How to parse JSON that is not defined in CodingKeys
Consider the following JSON:
{
"jsonName": "fluffy",
"color1": "Blue",
"color2": "Red",
"color3": "Green",
&...
0
votes
1
answer
58
views
Swift Converting Codable Variable to String Array [duplicate]
I'm following this tutorial on creating a collapsible TableView:
https://www.youtube.com/watch?v=Q8k9E1gQ_qg
He's loading a String array of names into the tableview like so:
struct ExpandableNames {
...
0
votes
1
answer
117
views
Immutable property will not be decoded because it is declared with an initial value which cannot be overwritten
I'm working on a new project and to take the advantage of the new features and resources available in Swift/SwiftUI for faster build and to minimize the app size, I'm only using the official libraries....
0
votes
0
answers
215
views
Swift - Codable "Number 2.87 is not representable in Swift"
I have the following struct:
struct CustomerEntries: Codable {
var date: String
var customer_rate: Double
var percentage: Double
enum CodingKeys: String, CodingKey {
case ...
0
votes
0
answers
54
views
How to support Any in codable?
I am trying to integrate SwiftData for storing data in my app, which currently uses objectmapper along with alamofire for mapping json data into models. For using swiftData, it requires that the ...
2
votes
0
answers
82
views
Issue parsing JSON data
Recently, I am facing issue in parsing the JSON into the model class.
{
"status": true,
"data": [
{
"id": "252",
"...
0
votes
1
answer
57
views
An escape character exists in the value of JSON, causing a decoding error
When data is provided from the server, an escape character is included, so an error occurs when decoding into Decodable type. Even if I change it to a dictionary using JSONSerialization, an error ...
0
votes
0
answers
47
views
How to make multiple existing SwitftData models to conform to Codable by inheriting from base class?
The following is my attempt (with ChatGPT 3.5's help) to implement a base class A: Codable with required init and func encode where I am trying to use reflection to findout B.property1 and C.property2 ...
0
votes
1
answer
103
views
Codable: Decode a String into a custom type (ISO 8601 Date, no time components)
Consider the following type:
public struct DocumentDate: Codable {
/// Year component of the date, Integer with no limitation on the range.
public let year: Int
/// Month component of the ...
2
votes
1
answer
58
views
Manually unwrapping JSON without codeable - Swift
I am trying to manually unwrap JSON without the use of codeable. I can get the top level to display but I can not get the beneficiary address to display. I know it's something in my model. I was ...
0
votes
0
answers
59
views
Convert JSON with variable property name to Swift object [duplicate]
How can I convert this response:
{"base":"USD","amount":1,"result":{"EUR":0.92,"rate":0.92251},"ms":1}
to Swift response model, ...
1
vote
0
answers
185
views
How can one persist an AttributedString within the SwiftData framework?
The problem of how to persist AttributedString data within the SwiftData framework isn't, as far as I can tell, specifically addressed anywhere. And since (custom) AttributedStrings address several ...
0
votes
0
answers
44
views
what's the best practice to define Model in swift
I have a model Answer like this
struct Answer: Codable {
var id: Int
var created: String
var modified: String
var updatedAt: String
var createdBy: String
...
}
And because I ...
0
votes
0
answers
134
views
Encoding CapturedRoomData with JSONEncoder
I used to be able to encode CapturedRoomData to Data using JSONEncoder with the following code:
// Encode CapturedRoomData
func encodeCapturedRoomData(_ roomData: CapturedRoomData) -> Data? ...
0
votes
3
answers
117
views
Create JSON from given data in Swift
I want to execute POST URLRequest but first I need to create request body.
The body should look like this:
{
"model": "gpt-4-vision-preview",
"messages": [
{
...
-1
votes
1
answer
99
views
Post method generic codable API response not coming properly in swift [closed]
I have created APINetworkManagerAll here i have created serviceCall and calling that in ViewController. here postGenericCall2() is called and response also coming but my given param values not coming ...
0
votes
3
answers
299
views
Unable to get SwiftData to store/retrieve CGPoint, CGSize, CGRect
I'm trying to get SwiftData to store Core Graphics base structures like CGSize, CGRect, CGPoint, but it doesn't work. I suppose CGVector and CGAffineTransform could be added to the list, but I haven't ...
0
votes
0
answers
46
views
In Swift, how can I use an alias name for the struct/class which is mapped to object returned in JSON (from WebAPI call)?
I am making a call to a WebAPI which returns the following JSON.
The JSON contains an object named group which I want to map in my Swift code using Codable protocol.
"group":{"ID":...
2
votes
1
answer
141
views
swift factory for decodable type to one of possible results
Note: saw this question but doesn't seem to resolve the issue:
Swift Dynamically choose Codable struct for JSON field value based on response type
I don't know the runtime type before hand since ...
0
votes
1
answer
84
views
FirestoreSwift DocumentReference codable
I have the following model:
struct Organization: Codable, Identifiable {
@DocumentID var id: String? <- Identifiable
let ref: DocumentReference <- Reference to the document
let name: ...
1
vote
2
answers
586
views
Swift 5.7, can you use a string to dynamically use a keyPath with Structs?
struct Server: Codable {
let cats: Int
let dogs: Int
let fishies: Int
}
It must be Codable.
let x = Server(cats: 42, dogs: 13, fishes: 777)
We can use keypaths:
print( x[keyPath: \.dogs] )
Which ...
2
votes
1
answer
60
views
Is there a way to iterate through a Codable (e.g. each item in a JSON parse)?
Say you're decoding a huge JSON file:
struct Examp: Codable {
let Cats: [CatsItem]
let Dogs: [DogsItem]
let Horses: [HorsesItem]
.. forty more
}
After you parse it, on the console you simply ...
0
votes
1
answer
112
views
Two Different models with the some of same properties cause problems in Swift
i have two different models with slightly different properties in my project. But when i use them without default values in one of the model, it gives error Type 'Instructions' does not conform to ...
1
vote
0
answers
368
views
SwiftData Model Inheriting from Codable Class
I have a backend written in swift (hosted on GCP Cloud Run, aka linux so no access to Apple-specific frameworks).
I have a regular codable class:
open class MyClass: Codable, Identifiable {
var id:...
1
vote
1
answer
144
views
How to pass CodingKeys into a function outside a class, as an array not an enum?
I have implemented custom JSON decoding for some classes in my project. I've set up the usual CodingKeys enum and implemented custom encode and decode functions. This all works fine.
But I've also ...
0
votes
0
answers
26
views
Adding @Model (SwiftData) causes error 'does not conform to Decodable/Encodable' [duplicate]
I have a class called Resource that maps across to some fairly complex JSON structure that I receive from the API. It has some nested properties and objects that I defined within my class. Everything ...
0
votes
1
answer
39
views
Facing difficulties to define a type for a specific key while decoding JSON
I have come across a key type in the JSON added bellow,
{
"id": "B2CAA3C8-077B-4A49-B5BA-206709630138",
"markAsDoneDate": null,
"endDate": 735025126....
0
votes
2
answers
787
views
SwiftData with Codable
I'm attempting to integrate SwiftData into my networking model to incorporate local persistence. In order to achieve this, I need to ensure that my Codable model conforms to SwiftData. However, I ...
-1
votes
1
answer
181
views
New to YAML: not parsing in Swift
Here's some yaml that I've generated :
byTeam:
- t0: { description: "Find a video of an object being selected and deselected", bestAnswer: [ 0 ]}
- t1: { description: "Reveal ...
1
vote
3
answers
253
views
In Swift, how do I decode both lower case and pascal case JSON using Decodable protocol?
Until recently, I have been able to decode both lower case ("fooBar") JSON and pascal case ("FooBar") JSON using the Decodable protocol by simply including a CodingKeys enum like ...
0
votes
2
answers
75
views
Data output via the Laravel API for a grouped collection
My problem is that I can't bring the output of a list of products grouped by category, for further deserialization in an iOS application using the Decodable protocol.
In my Laravel 10 application ...
-1
votes
1
answer
190
views
App crashing when decoding JSON data from UserDefaults and assigning decoded data to an array
I am a novice learning to code. I've set myself a challenge of creating an app and have been following along to books and also using ChatGPT for help creating code for things I don't currently know ...
1
vote
3
answers
388
views
Best way to map a JSON string to a custom enum case without having access to the enums implementation in Swift?
Consider the following simple JSON:
{
"title": "Some title",
"subtitle": "Some subtitle",
"button_type": "rounded"
}
This is my ...
1
vote
1
answer
73
views
A key in JSON response sometimes Int and sometimes comes as String [duplicate]
How to parse when data type of key is random sometimes comes as Int/string. Below is my code what have tried so far but not working:
do {
// let value = try String(container.decode(Int.self, ...
0
votes
0
answers
29
views
Missing argument for parameter 'from' in call. Insert 'from: <#Decoder#>' while model already consists of decoder
I am trying to create a variable and initializing it in the init of class that consists of first object of a Codable Struct Array
@Published private var CoreData: [WeatherModel]
self.model = CoreData....
0
votes
0
answers
27
views
Dynamic API response values for same Codable coding key in Swift [duplicate]
I'm decoding an API JSON response into a class called Company.
class Company: Codable {
let id: Int
let name: String?
...
}
One of the elements in the JSON response is called "...
1
vote
1
answer
66
views
SpriteKit SKScene initialization
I'm trying to convert my game to use Codable instead of NSCoding and Im having trouble with how to get a game scene initialized.
I've a class call GameScene and 2 subclasses called TownScene and ...
0
votes
0
answers
79
views
Swift array of Codable is not Codable [duplicate]
Apple's documentation on Codable states:
Built-in types such as Array, Dictionary, and Optional also conform to Codable whenever they contain codable types.
However, the following code snippet ...
-2
votes
2
answers
167
views
Mapping JSON Result to an Enum in Swift
I have the following response from JSON service:
[
{
"id": 1,
"name": "Student"
},
{
"id": 2,
"name": &...
0
votes
0
answers
22
views
Type 'SelectedDelieveryTimeDateSloteDS' does not conform to protocol 'Decodable' in swift
struct SelectedDelieveryTimeDateSloteDS: Decodable {
let method: String
let entityID: Int?
let name, methods: String?
let active: Bool
let sortOrder, futureDaysLimit, ...
-2
votes
1
answer
117
views
Accessing Nested Object in JSON array data
I have JSON data which has JSON objects in the array. I need to bind those properties to the buttons, so when a button is clicked, an Int value is given to it.
JSON data:
{
"id": 0,
&...
0
votes
0
answers
2k
views
SwiftUI ForEach indices error about expected argument type Binding<C>
I'm getting this error message:
Cannot convert value of type 'Range<Array<Cat>.Index>' (aka 'Range<Int>') to expected argument type 'Binding<C>'
On this ForEach line:
ForEach(...
0
votes
1
answer
143
views
Use Location wrapper to decode CLLocation variable
I am currently trying to make an extension to render CLLocation codable. To do so, I am trying to replicate the example on this thread: Swift - Codable Decode array of arrays of CLLocation
I have the ...
0
votes
1
answer
415
views
CodingKeyRepresentable for singleValueContainer
I'm a little stuck here. I have a struct with several fields codable to a string (below is similar example):
struct MyColor {
var red: UInt8
var green: UInt8
var blue: UInt8
}
extension MyColor:...
0
votes
1
answer
37
views
Why does @Published attribute cause this error: Type 'Booking' does not conform to protocol 'Decodable'
I ran into a weird problem. Just adding the attribute @Published causes this error: "Type 'Booking' does not conform to protocol 'Decodable'"
THIS compiles fine:
class Booking: ...
1
vote
0
answers
118
views
How can make Codable of type PhotosPickerItem?
I'm trying to save an array like PhotosPickerItem (instead of an array of images to save memory) in any available form, for example, through UserDefaults using Codable. However, I can't match the ...