初始化后更改通用属性的值 [英] Change value of generic property after initialization

查看:64
本文介绍了初始化后更改通用属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的结构,其中包含一个泛型:

Here's my struct that contains a generic:

struct SupportOptions<S> where S: ListStyle {
    var text: String = ""
    var listStyle: S
}

/**
 Allow initializing without a `listStyle` https://stackoverflow.com/a/64530006/14351818
 */
extension SupportOptions where S == InsetGroupedListStyle {
    init(text: String = "") {
        self.text = text
        self.listStyle = InsetGroupedListStyle()
    }
}

然后我像这样创建一个实例:

I then create an instance of it like this:

class ViewController: UIViewController {
    var options = SupportOptions()
}

但是,当我尝试更改options.listStyle时,它不起作用.

But, when I try changing options.listStyle, it doesn't work.

options.listStyle = InsetListStyle()

无法将"InsetListStyle"类型的值分配给"InsetGroupedListStyle"类型

Cannot assign value of type 'InsetListStyle' to type 'InsetGroupedListStyle'

推荐答案

当您不带参数调用SupportOptions()时,实际上是在为可选的text参数使用空字符串调用init(text :).您的init(text :)方法将通用约束S定义为InsetGroupedListStyle类型.一旦定义了通用约束,就不能将InsetGroupedListStyle实例分配给listStyle.这就是为什么您的InsetListStyle分配失败的原因.

When you call SupportOptions() with no arguments it's actually calling init(text:) with an empty string for the optional text argument. Your init(text:) method defines the generic constraint S to be of type InsetGroupedListStyle. Once your generic constraint is defined you can't assign anything other than an InsetGroupedListStyle instance to listStyle. That is why your InsetListStyle assignment is failing.

如果要将listStyle设置为InsetListStyle类型,则需要在实例化时指定它:

If you want listStyle to be of type InsetListStyle you need to specify that at the time of instantiation:

class ViewController: UIViewController {
    var options = SupportOptions(text: "", listStyle: InsetListStyle())
}

这篇关于初始化后更改通用属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆