How can I make the memberwise initialiser public, by default, for structs in Swift?(默认情况下,如何将成员初始化程序公开为 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 中的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:默认情况下,如何将成员初始化程序公开为 Swift 中的结构?
基础教程推荐
- iOS4 创建后台定时器 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01