So I have been trying to fix this problem that has been already discussed here for a few times but I cannot seem to truly understand where the issue comes from and how to fix it in my application. Apologies if this one is obvious but I've picked up SwiftUI a week ago.
Basically what I am doing here is that I have a function called countStrokes()
where I have an array of strings as an input. First of all I convert the array to an int array, then compute the sum of the array and return the sum as a String
.
After that I declare a new lazy var called strokes
and initialise it by calling the countStrokes()
function.
All I want to do in the View
is to print out the strokes value using the Text()
module.
Any ideas of how to modify my existing code will be much appreciated.
import SwiftUI
struct Skore: View {
@State var skore: [String]
lazy var strokes: String = countStrokes(array: skore)
var body: some View {
Text(strokes)
}
}
func countStrokes(array: [String]) -> String {
let newArray = array.compactMap{Int($0)}
let total = newArray.reduce(0, +)
let totalString = String(total)
return totalString
}
The simplest is just use function inline. As soon as your view depends on skore
state and countStrokes
depends on it, once skore
will be modified the corresponding Text
will be recalculated and shows correct result.
struct Skore: View {
@State var skore: [String]
var body: some View {
Text(countStrokes(array: skore))
}
}