How can I use function type?

Viewed 87

I want to know if there is a way to use a function Type as var, for example in this code I am trying to send a function to get triggered in a Button tap Action. Is this kind of programming even possible in Swift?

The down code is not working and It is for SwiftUI, but the question is applicable to Swift as well.

struct ContentView: View {

@State var backgroundColor: Color = Color.white

func backgroundColorFunction() { backgroundColor = Color.red }

var body: some View {
    
    ZStack {
        
        backgroundColor.ignoresSafeArea()
        
        CustomView(incomingFuction: backgroundColorFunction()) // :Here
        
    }
    

}
}



struct CustomView: View {

var incomingFuction: ???funcType??? = ???funcType???()

var body: some View {
    

    Button("update Background Color") {
        
        incomingFuction()
        
    }
   
    }
}
1 Answers

Yes, it is possible, moreover it is widely used, especially in SwiftUI.

Here is your updated code:

struct FuncContentView: View {
    
    @State var backgroundColor: Color = Color.white
    
    func backgroundColorFunction() { backgroundColor = Color.red }

    var body: some View {
        ZStack {
            backgroundColor.ignoresSafeArea()
            
            CustomView(incomingFuction: backgroundColorFunction) // << here !!
        }
    }
}

struct CustomView: View {
    
    var incomingFuction: () -> ()   // << here !!
    
    var body: some View {
        Button("update Background Color") {
            incomingFuction()
        }
    }
}
Related