16

I am having a little trouble here: I have a class

class TempC {
    func GetData(){
          //do stuff
    }
}

And in ContentView I want to call the function, but I can't manage to do it, I am getting errors...

struct ContentView: View {

var variable : TempC
variable.GetData()
var body: some View {
        Text("Hello World")
    }
}

Or in any other method. How can I call an external function now?

PS: The error that I get are on the line with variable.GetData() which are:

  1. Consecutive declarations on a line must be separated by ";"
  2. Expected "("in argument list of cantons declaration
  3. Expected "{"in body of function declaration
  4. Expected 'func' keyword in instance method declaration
  5. Invalid redeclaration of 'variable()'

It's like it is expecting to create a new function not to get the one that is already existing.

0

1 Answer 1

31

Depending on what your going to do in that call there are options, ex:

Option 1

struct ContentView: View {

    let variable = TempC()
    init() {
        variable.GetData()
    }
    var body: some View {
            Text("Hello World")
    }
}

Option 2

struct ContentView: View {

    let variable = TempC()

    var body: some View {
        Text("Hello World")
        .onAppear {
            self.variable.GetData()
        }
    }
}

Similarly you can call it in .onTapGesture or any other, pass reference to your class instance during initialising, etc.

Sign up to request clarification or add additional context in comments.

2 Comments

Good response! Was used with the UIKIT style of calling functions and methods, here I see I need to make an action or something.
What if variable.GetData() return a tuple then how to access it in var body: some View

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.