Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 511
Derick Mathews Avatar asked Mar 23 '20 14:03

Derick Mathews


1 Answers

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.

like image 113
KevinP Avatar answered Nov 02 '22 22:11

KevinP