swift - 对于 Swift 中的结构,如何默认公开成员初始化器?

标签 swift initialization

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

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

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

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

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

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

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

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 的情况下做到这一点?

最佳答案

引用手册:

"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."

摘自 "The Swift Programming Language" , 第 "Access Control" .

关于swift - 对于 Swift 中的结构,如何默认公开成员初始化器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26224693/

相关文章:

Swift 三重箭头符号

ios - 如何使用 UISearchBar 过滤 NSDictionary?

java - 为什么我们需要初始化 block 的例子

java - 无法定义私有(private)静态最终变量,因为它会引发异常

c++ - 继承的 const 属性和初始化(错误?)

ios - Swift 4 字典 [字符串 : AnyObject] sort by key in alphabetical order

ios - 没有渲染/虚拟内容的 ARKit/SceneKit 截图

c# - 如何告诉编译器必须初始化属性

swift - Swift 的大小方法采用 `Int` s 的基本原理是什么?

C# - 初始化程序中类字段的闭包?