我知道这是一个奇怪的标题,但有很多帖子的标题相似,但完全不同的问题.大多数人在他们的视图中编写其他东西,而不是View
个代码,这是我没有做的(据我所知).
我正在try 让Picker
与其他BinaryInteger
类型兼容,因为除了Int
之外,它不能与其他任何类型兼容,而且我在使用预览时遇到了一些问题.代码如下:
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