提问人:David.C 提问时间:3/10/2023 最后编辑:David.C 更新时间:3/22/2023 访问量:156
具有协议类型的 Swiftui 选取器 - 编译器无法对此表达式进行类型检查
Swiftui Picker with protocol type - Compiler is unable to type-check this expression
问:
鉴于这个符合协议的结构Relationable
struct RomanticRelation: Relationable{
typealias Relationship = RomanticRelationType
typealias Relation = RomanticRelation
var nickname: String
var lastInteracted: Date
var relationship: RomanticRelationType = .couple //Enum type
}
protocol Relationable {
associatedtype Relation
associatedtype Relationship:Hashable //Enum
var nickname:String { get set }
var lastInteracted:Date { get set }
var relationship:Relationship { get set }
var typicalInterests:[String] { get }
var interests:[String] { get set }
}
而这个变量在符合Published
ObservableObject
class RelationsViewModel: ObservableObject {
@Published var selectedRelation: any Relationable = PersonalRelation()
}
变量是符合 和relationship
Enum
CaseIterable
Hashable
enum RomanticRelationType:Hashable, CaseIterable {
case couple, married, engaged
var title: String {
switch self {
case .couple:
return "Couple"
case .married:
return "Married"
case .engaged:
return "Engaged"
}
}
var priority: Int {
switch self {
case .couple:
return 3
case .engaged:
return 2
case .married:
return 1
}
}
}
如果我有 3 个结构体符合协议,每个结构体都有这个变量(关系),我想将其分配给选择而不是制作 3 个Picker
Picker
从协议中分配已知类型(String)时,其工作
TextField("Nickname", text: $relationsVM.selectedRelation.nickname)
.modifier(TextFieldModifier(width: 250, height: 30))
.padding(.top)
但是,使用选择器,它将不起作用
Picker("Type", selection: $relationsVM.selectedRelation.relationship) {
//ForEach got a simple string array
ForEach(relationsVM.allRelationships) { relationType in
Text(relationType)
}
}.pickerStyle(.menu)
编译器无法进行类型检查和编译,我知道这是因为选择器的参数,也许需要在某处强制转换类型?selected
答: 暂无答案
评论
selection
Relationable
RelationsViewModel
RomanticRelationType
Picker
String
Relationship
associatedtype
rawValue
Int
Int