6
votes

I am using SwiftUI/Swift for a week now, and I love it. Now I have a problem. I want to call a Function from my View, but I get this Error

Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols

This is the Code:

struct testView: View {
    
    
    var body: some View {
        VStack {
            Text("TextBox")
            Text("SecondTextBox")
            self.testFunction()
        }
    }
    
    func testFunction() {
        print("This is a Text.")
    }
    
}

I don't get it. In other languages its much simpler and could work that way. Can anybody help me please? Swift is pretty new to me :D

3
It is not clear what are you going to do with that function and at which moment, because in context of body mostly expected only views. So would you elaborate more?Asperi
Im just playing around with SwiftUI. I tried to execute a for in the View, but I couldn't. Is there a way to execute functions or for's in a View?yama_HD

3 Answers

14
votes

Meanwhile here are the places (not all) where/how you can call a function

    init() {
        self.testFunction()     // non always good, but can
    }

    var body: some View {
        self.testFunction()            // 1)
        return VStack {
            Text("TextBox")
               .onTapGesture {
                  self.testFunction()    // 2)
               }
            Text("SecondTextBox")
        }
        .onAppear {
            self.testFunction()     // 3)
        }
        .onDisappear {
            self.testFunction()     // 4)
        }
    }

... and so on

1
votes

There is a reason, when writing in swift UI (iOS Apps), that there is a View protocol that needs to be followed. Calling functions from inside the structure is not compliant with the protocol.

The best thing you can do is the .on(insertTimeORAction here).

Read more about it here

0
votes

Using Swift 5.3 and Xcode 12.4

I use a little extension to debug inside the Views (VStack in the example), e.g. to inspect a geometryReader.size. It could be used to call any function in the View as follows:

NOTE: For debugging purposes only. I don't recommend including code like this in any production code

VStack {
    Text.console("Hello, World")
    Text("TEXT"
}

extension Text {
    static func console<T>(_ value: T) -> EmptyView {
        print("\(value)")
        return EmptyView()
    }
}

This will print "Hello, World" to the console.....