Is something to work with data like COBOL


I think COBOL is a data centric programming language. Some features are nice and one of this is to "read data into" data structure. If data structure is a group the check on data is later at the point of using. The feature is that I did not to know datatypes or convert something at the time I fill my data structure.

If I think in Swift I need something like read Data into struct or create struct from Data...


struct dataContainer { // declare like data group in COBOL
var x : [UInt8] = Array (count:15, repeating = 0)
var u : UInt64
var b : Int16
var k : [UInt8] = Array (count: 27, repeating = 0)

func main () {
let fh = FileHandle ("dummyData")
let flatData : Data (sizeof (DataContainer).fromFileHandle() // read from file data
let myStruct = DataContainer (flatData)

print ("Numeric or error = (myStruct.u)")

Is something like this existing or how to do something like this?

I hope problem is clearly explained

1 Like

I'm afraid it is not :smiley:

  • is it a fixed size data structure or not / don't care?
  • do you need array semantics for your "x" and "k" variables or don't really care?
  • do you want array of 27 UInt8 bytes or a String really?
  • do you want to see a binary format on disk or does that not matter?
  • if binary do you need that format be compatible with different endian devices?
  • do you want to read or write as well?
  • do you want to read from files only or remote URLs as well?

Here's just one (out of many) possible answers to your question:

struct DataContainer {
    var x: [UInt8] // not String?
    var u: UInt64
    var b: Int16
    var k: [UInt8]

extension DataContainer: Codable {
    init(from file: URL) throws {
        let data = try Data(contentsOf: file) // DON'T USE THIS IN PRODUCTION FOR REMOTE URL's
        self = try JSONDecoder().decode(Self.self, from: data)
    func save(to file: URL) throws {
        let data = try JSONEncoder().encode(self)
        try data.write(to: file) // DON'T USE THIS IN PRODUCTION FOR REMOTE URL's

let data = try! DataContainer(from: file) file2)

See a somewhat related question recently discussed, yet it can be miles away from what you are after. There the data structure is externally specified, a fixed binary format.

1 Like

it helps, thank you