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.
I would change constants to enum first of all:
Second: depending on nature of the variables, your
structcould 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:In separate file:
So you use it like this:
And as a side effect your
structwill now be much shorter. And needless to say all the definitions are in separate files.