默认情况下,如何在Swift中将成员初始化器公开给结构体? [英] How can I make the memberwise initialiser public, by default, for structs in Swift?

查看:94
本文介绍了默认情况下,如何在Swift中将成员初始化器公开给结构体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个定义结构的快速框架:

I have a swift framework that defines a struct:

public struct CollectionTO {
    var index: Order
    var title: String
    var description: String
}

但是,我似乎无法使用导入该库的另一个项目中的隐式成员明智的初始化器.错误是"CollectionTO"无法初始化,因为它没有可访问的初始化程序.也就是说,它没有为默认的隐式成员明智的初始化程序提供public关键字.

However, I can't seem to use the implicit member wise initializer from another project that imports the library. The error is 'CollectionTO' cannot be initialised because it has no accessible initialisers. i.e. it's not giving the default implicit member wise initialiser the public keyword.

var collection1 = CollectionTO(index: 1, title: "New Releases", description: "All the new releases")

我必须像这样添加自己的初始化方法:

I'm having to add my own init method like so:

public struct CollectionTO {
    var index: Order
    var title: String
    var description: String

    public init(index: Order, title: String, description: String) {
        self.index = index;
        self.title = title;
        self.description = description;
    }

}

...但是我宁愿不知道是否还有其他人知道的方式?

... but i'd rather not if there is another way anyone knows?

推荐答案

引用手册:

结构类型的默认成员方式初始化程序 如果任何结构的存储属性都是私有的,则该结构类型的默认成员初始化器被认为是私有的.否则,初始化程序的访问级别为internal.

"Default Memberwise Initializers for Structure Types The default memberwise initializer for a structure type is considered private if any of the structure’s stored properties are private. Otherwise, the initializer has an access level of internal.

与上面的默认初始值设定项一样,如果您希望将公共结构类型在另一个模块中使用时以成员方式初始值设定项进行初始化,则必须自己提供公共成员身份初始值设定项作为类型定义的一部分."

As with the default initializer above, if you want a public structure type to be initializable with a memberwise initializer when used in another module, you must provide a public memberwise initializer yourself as part of the type’s definition."

摘录自"Swift编程语言" .

这篇关于默认情况下,如何在Swift中将成员初始化器公开给结构体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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