Hi,
Recently I was writing classes to capture data of different types and output them as fixed length fields in a number of different fixed length records. I was working in Delphi, but wondering if Swift would be able to make it better. Each record class needed to mention each record 3 times: declaring a class variable to represent the field, then creating the object, then initialising it with a value from a database. The order of creation of the field objects is key because that determines the order they appear in in the output file.
I was thinking that with Swift I could have reduced the number of mentions by name of these field objects, and thus the number of places where mistakes could be made or just reduce the tedium of programming it. There are probably a couple of hundred fields to be declared, so it would be great to be able to create them in the same statement as they are declared in. But they have to be added to an array that belongs to the record class, which at present you can't do
A simple convention that could be observed is that properties of a class are evaluted from top to bottom and anything with an assignment can be used in initialising later properties. Here's some simplified code along the same lines as what I was doing:
class Field {
var length: Int
var mandatory: Bool
var value: String = ""
init(inout list: [Field], length: Int, mandatory: Bool){
self.length = length
self.mandatory = mandatory
list.append(self)
}
}// Field
class Record {
var items = [Field]() // This is now validly initialised, so should be available in subclasses.
var length: Int
init(length: Int) {
self.length = length
}
func write(fileName: String) {
// open file
for field in items {
write(field)
}
}
private func write(field: Field) {
// Do stuff
}
}// Record
class PersonRecord: Record {
var nameField = Field(list: &items, length: 20, mandatory: true) // Use the items member of the superclass.
var addressField = Field(list: &items, length: 20, mandatory: false)
var phoneField = Field(list: &items, length: 20, mandatory: true)
/// Plus another 20 or so fields
}// PersonRecord
// Plus another 10 or so record classes.