Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols calling calling functions with swift ui

20,039

Your MyWatchView.self.playSound() function is not returning a View therefore you cant use it inside your HStack.

Without seeing your full code I can only assume what you want to do, but heres my guess: if the state variable play is true you want to execute the func playSound()?

You could do something like this:

@State private var play = false {
    willSet {
        if newValue {
            WKInterfaceDevice.current().play(.failure)
        }
    }
}

This will execute your static func whenever the State variable play changes to true.

Share:
20,039
Derick Mathews
Author by

Derick Mathews

Updated on July 06, 2020

Comments

  • Derick Mathews
    Derick Mathews almost 4 years

    I have a SwiftUI View called MyWatchView with this stack:

    VStack (alignment: .center)
    {
        HStack
        {
            Toggle(isOn: $play)
            {
                Text("")
            }
            .padding(.trailing, 30.0)
            .hueRotation(Angle.degrees(45))
            if play
            {
                MyWatchView.self.playSound()
            }
        }
    }
    

    It also has @State private var play = false and a function playSound like this:

    static private func playSound()
    {
        WKInterfaceDevice.current().play(.failure)
    }
    

    I am getting an error of Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols I think this is probably something that I am not understanding in the way structs work in Swift.

  • KevinP
    KevinP about 4 years
    @Asperi I would very much appreciate it if you would instruct me. It worked on my test application. :)
  • Derick Mathews
    Derick Mathews about 4 years
    Thank you for your answer but how could I do this with the function? I am trying to use a timer to trigger the play sound function. This is my code in my View Controller Class from my iOS app timer = Timer.scheduledTimer(timeInterval: interval, target: click class, selector: #selector(clickClass.repeatSound), userInfo: clickClass, repeats: switchView.isOn)