如何自动为Swift类创建一个初始化器? [英] How to automatically create an initializer for a Swift class?
问题描述
更新: 使用结构而不是类. Struct在许多方面都更好,它拥有自己的初始化程序.
UPDATE: Use structs and not classes. Struct is better in many ways has got an initializer of its own.
这是我的模型课.是否可以自动创建init
方法?每次我必须一一初始化所有变量时,会花费很多时间.
This is my model class. Is it possible to create the init
method automatically? Everytime I have to initialize all the variables one by one and it costs a lot of time.
class Profile {
var id: String
var name: String
var image: String
init(id: String, name: String, image: String) {
self.id = id
self.name = name
self.image = image
}
}
我希望self.id = id
和其他变量自动初始化.
I want self.id = id
and other variables to initialize automatically.
推荐答案
更新自Xcode 11.4起
Update As of Xcode 11.4
您可以refactor
(鼠标右键单击菜单)生成类和结构memeberwise initializer
.
You can refactor
(right-click mouse menu) to have generated class and struct memeberwise initializer
.
注意:struct
自动初始化程序是内部的.您可能会在编写将模块制作为public
的模块时生成memeberwise initializer
.
Note: struct
auto inititializers are internal. You may what to generate memeberwise initializer
when you writing a module to make it public
.
右键单击>重构>生成成员初始化"
Right-click > Refactor > 'Generate Memberwise Initialization'
对于较早的Xcodes
有一个方便的Xcode插件: https://github.com/rjoudrey/swift-init-generator 或 https://github.com/Bouke/SwiftInitializerGenerator
There is a handy plugin for Xcode: https://github.com/rjoudrey/swift-init-generator or https://github.com/Bouke/SwiftInitializerGenerator
感谢插件创建者.
这篇关于如何自动为Swift类创建一个初始化器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!