【发布时间】:2020-10-26 07:55:50
【问题描述】:
我想将ListStyle 存储在SupportOpts 内的属性中,因此我将<S> 和where S: ListStyle 添加到结构声明中(来自此answer)。
struct SupportOpts<S> where S: ListStyle {
var title: String = "Placeholder"
var listStyle: S = InsetGroupedListStyle() as! S /// had to put an `as! S` or else it couldn't compile
}
我可以这样创建一个实例:
let options: SupportOpts = SupportOpts(
title: "Title",
listStyle: InsetGroupedListStyle()
)
但是,当我删除InsetGroupedListStyle() 时(我已经在SupportOpts 中设置了默认值):
let options: SupportOpts = SupportOpts(
title: "Title"
)
我明白了:
无法推断泛型参数“S”,显式指定泛型参数以解决此问题 [修复]
所以我按下了“修复”按钮,现在它正在等待 S: ListStyle:
我应该在这里放什么?
let options: SupportOpts = SupportOpts<ListStyle>(title: "Title")
/// Error: Value of protocol type 'ListStyle' cannot conform to 'ListStyle'; only struct/enum/class types can conform to protocols
let options: SupportOpts = SupportOpts<S>(title: "Title")
/// Error: Cannot find type 'S' in scope (well that's kind of obvious...)
let options: SupportOpts = SupportOpts<InsetGroupedListStyle>(title: "Title")
/// this works...
我是否必须指定SupportOpts<InsetGroupedListStyle>(title: "Title"),即使我已经在SupportOpts 中设置了默认值?
【问题讨论】: