I have a struct that I'd like to include a calculated property in, but I'm not sure how to initialise/set up the property as it's based on another property which is also a struct:

```
struct Session {
let weekNumber: Int
let dayNumber: Int
let sets: Int
let totalTime: Double
let phases: [Phase]
struct Phase {
let order: Int
let time: Double
let label: String
}
}
```

I would like totalTime to be calculated as the sum of phases.time. Is this possible?

You can do something like that. That calculates only once.

```
struct Session {
let weekNumber: Int
let dayNumber: Int
let sets: Int
let totalTime: Double
let phases: [Phase]
init(weekNumber: Int,
dayNumber: Int,
sets: Int,
totalTime: Double,
phases: [Phase]) {
self.weekNumber = weekNumber
self.dayNumber = dayNumber
self.sets = sets
self.phases = phases
self.totalTime = phases.reduce(0) { $0 + $1.time } // Sum every phase
}
struct Phase {
let order: Int
let time: Double
let label: String
}
}
```

Or you can do using computed property. That calculates every time it is called.

```
struct Session {
let weekNumber: Int
let dayNumber: Int
let sets: Int
var totalTime: Double {
return phases.reduce(0) { $0 + $1.time } // Sum every phase
}
let phases: [Phase]
struct Phase {
let order: Int
let time: Double
let label: String
}
}
```

1 Like