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

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

问题描述

更新:使用结构而不是类.结构在很多方面都更好,它有自己的初始化器.

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.

推荐答案

更新 As of Xcode 11.4

Update As of Xcode 11.4

您可以重构(鼠标右键菜单)生成类和结构memeberwise initializer.

You can refactor (right-click mouse menu) to have generated class and struct memeberwise initializer.

注意:struct 自动初始化器是内部的.在编写模块以使其public 时,您可能需要生成memeberwise 初始化程序.

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'

对于较旧的 Xcode

Xcode 有一个方便的插件:https://github.com/rjoudrey/swift-init-generatorhttps://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天全站免登陆