Function is being called multiple times

Hi everyone,

I’m trying to figure out why the loadQuestions(from:) function is being triggered multiple times, even though the button that initiates the view is tapped only once. According to the Xcode console, the function is being called 9 times.

Here’s the relevant code:

var loadQuestionsCallCount = 0

func loadQuestions(from fileName: String) -> [Questions] {
    loadQuestionsCallCount += 1
    print("loadQuestions called \(loadQuestionsCallCount) time(s) — file: \(fileName)")
    do {
        return try Bundle.main.decode(file: fileName)
    } catch {
        return []
    }
}

private var tests: [Questions] {
    switch practiceNumber {
    case 1:
        return loadQuestions(from: "test1.json")
    case 2:
        return loadQuestions(from: "test2.json")
    case 3:
        return loadQuestions(from: "test3.json")
    default:
        return []
    }
}

The tests property is then accessed in the view like this:

VStack {
    ScrollView {
        if currentIndex < tests.count {
            let currentQuestion = tests[currentIndex]
            // ...
        }
    }
}

Any insight into how I can optimize this and prevent the function from being triggered repeatedly would be greatly appreciated.

Thank you in advance!

It’s a computed property, meaning it gets called each time you access tests. Given that you are iterating over it, it will gets called at least N*2 times inside scroll view, where N is the count of elements in tests. You need to create array once and store to avoid this.

2 Likes