Home > OS >  How to break up large struct in Swift
How to break up large struct in Swift

Time:06-26

I have a struct with 120 variables and 70 constants (is translation from FORTRAN physiological model); I would like to get the initializations and even the declarations out of the struct code because the file will be several thousand lines of code from the algorithms of the model. Here is some code that I thought would work by using a protocol and extension:

import Foundation

protocol HasConstants {
    var c1:Double {get set}
    var c2:Double {get set}
}

extension HasConstants {
    func setConstants() -> () {
        var c1 = 3.4
        var c2 = 9.9
    }
}

struct macPuf: HasConstants {
    var c1: Double
    var c2: Double
    setConstants()
}

This does not work. The compiler complains in the extension function that the variables are never used, and in the MacPuf struct it expects a func keyword and brackets, etc. in what it says is an instance method declaration.

Basically I would like to be able to have something like:

struct macPuf {
#include InitializeConstants. // for example c1
#include InitializeVariables. // for example var1 .. var45
var1 = var2 * c1
etc.
#include AnotherChunkOfCodeFromExternalFile
var 45 = functionX(var4   var 6)
etc.

I apologize that this is probably a ludicrous question with a ridiculously simple solution. Any assistance is greatly appreciated.

CodePudding user response:

I would change constants to enum first of all:

enum Constants: Double {
    case c1 = 3.4
    case c2 = 9.9
    // ...
}

Second: depending on nature of the variables, your struct could include either array or dictionary of the variables, instead of each variable as a property. That way you will only have variables needed for each instance. For example you could make variable name an enum as well to serve as a dictionary key, and variable value will be a dictionary value:

enum VariableName {
    case var1
    case var2
    // ...
}

struct MacPuf {

    var fields: [VariableName: Double]
    //...
}

In separate file:

extension MacPuf {

    func addField(_ name: VariableName, value: Double) {
        fields.update(value for: name)
    }

    func value(for name: VariableName) -> Double? {
        return fields[name]
    }
}

So you use it like this:

let macPuf = MacPuf()
macPuf.addField(.var1, value: macPuf.value(for: .v2)   Constants.c1.rawValue)

And as a side effect your struct will now be much shorter. And needless to say all the definitions are in separate files.

CodePudding user response:

Thanks. I appreciate all the replies.

  • Mike
  • Related