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

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

问题描述

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

I have a Swift framework that defines a struct:

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

但是,我似乎无法使用导入库的另一个项目中的隐式成员初始化程序.错误是:

However, I can't seem to use the implicit memberwise initialiser from another project that imports the library. The error is:

'CollectionTO' 无法初始化,因为它没有可访问的初始化程序

'CollectionTO' cannot be initialised because it has no accessible initialisers

即默认的合成成员初始化器不是 public.

i.e. the default synthesized memberwise initialiser is not public.

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;
    }
}

...但是有没有办法在不明确定义 public init 的情况下做到这一点?

... but is there a way to do this without explicitly defining a public init?

推荐答案

引用手册:

"结构类型的默认成员初始化器如果结构的任何存储属性是私有的,则结构类型的默认成员初始化器被认为是私有的.否则,初始化程序的访问级别为 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天全站免登陆