在Swift中,如何快速设置实例变量?

时间:2015-07-21 20:47:16

标签: ios swift

public class User {
    var id: Int
    var fb_id: String?
    var first_name: String?
    var last_name: String?
    var age: Int?
    var distance: Int?
    var login_at_pretty: String?
    var login_at: Int?
    var profile: Profile?
    init(id: Int, fb_id: String?, first_name: String?, last_name: String?, age: Int?, distance: Int?, login_at_pretty: String?, login_at: Int?, profile: Profile?){

        self.id = id
        if let fb_id = fb_id {
            self.fb_id = fb_id
        }
        if let first_name = first_name {
            self.first_name = first_name
        }
        if let last_name = last_name {
            self.last_name = last_name
        }
        if let age = age {
            self.age = age
        }
        if let distance = distance {
            self.distance = distance
        }
        if let login_at_pretty = login_at_pretty {
            self.login_at_pretty = login_at_pretty
        }
        if let login_at = login_at {
            self.login_at = login_at
        }
        if let profile = profile {
            self.profile = profile
        }
    }
}

这是最快捷的方式吗?我觉得我在打字。

1 个答案:

答案 0 :(得分:7)

对于你的班级,你正在做很多if-let语句,这些语句没有提供任何有用的东西。即:

   if let fb_id = fb_id {
        self.fb_id = fb_id
   }

fb_idself.fb_id是选项,因此不需要绑定。只是做:

self.fb_id = fb_id

但是,如果您没有计划进行子类化,那么使用struct会自动提供成员初始化程序:

public struct User {
    var id: Int
    var fb_id: String?
    var first_name: String?
    var last_name: String?
    var age: Int?
    var distance: Int?
    var login_at_pretty: String?
    var login_at: Int?
    var profile: Profile?
}

swift docs

中查看Memberwise Initializers for Structure Types