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

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

问题描述

我有一个定义结构的 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")

我必须像这样添加我自己的 init 方法:

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天全站免登陆