如何自动为Swift类创建一个初始化器? [英] How to automatically create an initializer for a Swift class?

查看:109
本文介绍了如何自动为Swift类创建一个初始化器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新: 使用结构而不是类. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆