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

1

8

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.

Ellieellinger answered 23/3, 2020 at 14:45 Comment(0)
H
5

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.

Henchman answered 23/3, 2020 at 14:57 Comment(2)
@Asperi I would very much appreciate it if you would instruct me. It worked on my test application. :)Henchman
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)Ellieellinger

© 2022 - 2024 — McMap. All rights reserved.