SwiftUI中Type '()'无法遵循View协议问题排查(确为View代码)
SwiftUI 自定义Picker兼容BinaryInteger类型的问题
我知道这个标题有点奇怪,但很多类似标题的帖子对应的问题都和我的不一样——大多是在视图里写了非View代码,但我没这么做(至少我自己是这么认为的)。我想让SwiftUI的Picker支持Int以外的BinaryInteger类型,但预览时出了问题,代码如下:
import SwiftUI struct CompatibilityPicker<Label, SelectionValue, Content> : View where Label : StringProtocol, SelectionValue : BinaryInteger, Content : View { var content : () -> Content var label : Label @Binding private var _selection : SelectionValue private var selection: Binding<Int> { Binding<Int>( get: { Int(_selection) }, set: { self._selection = SelectionValue($0) }) } init(_ label : Label, selection : SelectionValue, content : @escaping () -> Content) { self.label = label self._selection = selection self.content = content } var body: some View { Picker(label, selection: selection, content: content) } } struct CompatibilityPicker_Previews: PreviewProvider { @State static var selection : UInt8 = 4 static var previews: some View { CompatibilityPicker("Difficulty", selection: selection) { //error : Type'()' cannot conform to 'View' Text("Easy").tag(0) Text("Normal").tag(1) Text("Hard").tag(2) } } }
为什么会这样?我用完全相同的语法写的常规Picker能正常运行,不知道哪里错了。
感谢@RobMayoff的解决方案,我往前推进了一步,但出现了一些就算用cmd+shift+k清理缓存也消不掉的离谱错误:
init(_ label : Label, selection : SelectionValue, @ViewBuilder content : @escaping () -> Content) { self.content = content self.label = label self._selection = selection //variable self._selection used before initialised // This stays on this line if I change the order, } // Return from initializer without initialising all stored properties // That is not true, as far as I can tell
内容的提问来源于stack exchange,提问作者Ter Maxima
相关产品推荐
相关产品推荐

