UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 35 Consolidation Project: How to take a function and input it as a parameter?

Forums > 100 Days of SwiftUI

I have made 2 functions to deal with actually typing out the multiplication table till 12. I am trying to pass the functions as a parameter for my struct that will generate the math problems for the user. I am also trying to get the user's input from the content view and pass it as a parameter into my functions. My code is below:

//
//  ContentView.swift
//  HWSChallenge3
//
//  Created by Raszion23 on 11/19/20.
//

import SwiftUI

struct ContentView: View {

    @State var multiplicationTable = 4
    @State private var numberOfQuestionsBinding = 2
    @State private var mathProblem = "2 x 2"
    @State private var answer = ""
    @State private var isEditing = false
    let numberOfQuestions = ["5", "10", "15", "20", "All"]

    var body: some View {
        NavigationView {
            VStack {
                Form {
                    Section(header: Text("Select multiplication table")) {
                        Stepper(value: $multiplicationTable, in: 1 ... 12) {
                            Text("\(multiplicationTable)")
                        }
                    }

                    Section {
                        Picker(selection: $numberOfQuestionsBinding, label: Text("Select number of questions")) {
                            ForEach(0 ..< numberOfQuestions.count) {
                                Text("\(numberOfQuestions[$0])")
                            }
                        }
                    }

                    Text("\(mathProblem)")

                    TextField("Answer", text: $answer)
                        .keyboardType(.numberPad)

                    Section {
                        Button(action: {}, label: {
                            Text("Calculate")
                        })
                    }
                }
            }
        }
        .navigationBarTitle("iMultiply")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
//
//  MathProblem.swift
//  HWSChallenge3
//
//  Created by Raszion23 on 11/19/20.
//

import Foundation

struct MathProblem {

    let table: Int
    let problem: [String]
    let answer: [String]

    init(table: Int, problem: [String], answer: [String]) {
        self.table = table
        self.problem = problem
        self.answer = answer
    }
}
//
//  MathProblemBrains.swift
//  HWSChallenge3
//
//  Created by Raszion23 on 11/19/20.
//

import Foundation

struct MathProblemBrains {
    let content = ContentView()

    init(content: ContentView) {
        self.content = content
    }

    let math = MathProblem(table: content.multiplicationTable, 
                                              problem: timeTableProblems(content.multiplicationTable), 
                                              answer: timeTableProblems(content.multiplicationTable))

    func timeTableProblems(a: Int) -> [String] {
        var arrayOfProblems = [String]()
        var problem: String

        for i in 1 ... 12 {
            problem = "\(a) x \(i)"
            arrayOfProblems.append(problem)
        }

        return arrayOfProblems
    }

    func timeTableSolutions(a: Int) -> [String] {
        var results = [String]()
        var product: Int

        for i in 1 ... 12 {
            product = a * i
            results.append(String(product))
        }

        return results
    }
}

3      

First, since you are not doing any special initialization within your init you can remove it. Swift struct have a default initializer.

Second, you need to change your MathProblem. You don't need it to store a table, or an array of problem and answer. Each MathProblem has one problem (or text) and one answer. This will help you in the setup, and making the app work as intended. So it becomes:

struct MathProblem {
    var problem: String
    var answer: String
}

Third, you have 2 functions, one to populate problems, and one for answers, but by doing the above, we can now store all the problems in a [MathProblem] array. Which means we can bundle them inside one function which we can declare within ContentView. This function will need to return an array of MathProblem:

    func createTimesTable(for a: Int) -> [MathProblem] {
        var problem: String
        var product: String
        var questions = [MathProblem]()

        for i in 1...12 {
            problem = "\(a) x \(i)"
            product = "\(a * i)"
            questions.append(MathProblem(problem: problem, answer: product))
        }
        return questions
    }

Also note, this way when we call the function it reads nicely: createTimesTable(for: 5)

side note: You could also use an enum outside of ContentView if you prefer (in which case you declare the function as static)

So really, just declare the function inside ContentView and you're set. Now what you will need inside Content view, is a property to store this newly created times table array. And just a quick show of how you can use them:

// Just An Example For Show

let tenTimesQuestions = createTimesTable(for: 10)

let testQuestion = tenTimesQuestions[2]

print("Question: \(testQuestion.problem), Answer: \(testQuestion.answer)")

I hope this helps you figure out the rest of the challenge.

4      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.