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

Derick Mathews picture Derick Mathews · Mar 23, 2020 · Viewed 16.9k times · Source

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.

Answer

KevinP picture KevinP · Mar 23, 2020

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.