类型 '()' 不能符合 'View';只有 struct/enum/class 类型可以符合使用 swift ui 调用调用函数的协议

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

我有一个名为 MyWatchView 的 SwiftUI 视图,其中包含此堆栈:

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

它还有 @State private var play = false 和一个函数 playSound 像这样:

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

我收到 Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols 错误 我认为这可能是我不理解结构在 Swift 中工作的方式。

您的 MyWatchView.self.playSound() 函数未返回视图,因此您不能在 HStack 中使用它。

在没有看到你的完整代码的情况下,我只能假设你想做什么,但这是我的猜测:如果状态变量 play 为真,你想执行 func playSound() 吗?

你可以这样做:

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

每当 State 变量 play 变为 true 时,这将执行您的静态函数。