如何快速初始化一个空对象?这就是我所拥有的,但它也想要参数
var userInfo:User = User()
init(email: String, isVerified: String, profileImageURL: String, reputation: String, twitterHandle: String, userName: String) {
self._email = email
self._isVerified = isVerified
self._profileImageURL = profileImageURL
self._reputation = reputation
self._twitterHandle = twitterHandle
self._userName = userName
}
答案 0 :(得分:1)
使用此类可选属性创建类/结构
struct Employee {//struct or class
var name: String?
var number: String?
var position: String?
}
然后,您可以创建一个没有任何值的,具有某些值的对象
let emp = Employee()
let emp = Employee(name: nil, number: nil, position: nil)
let emp = Employee(name: "abc", number: nil, position: "xyz")
通过创建具有默认值参数的init方法,可以在创建对象时忽略
struct Employee {
var name: String?
var number: String?
var position: String?
init(name: String? = nil, number: String? = nil, position: String? = nil) {
self.name = name
self.number = number
self.position = position
}
}
let emp = Employee()
let emp = Employee(name: "abc", number: "124", position: "xyz")
let emp = Employee(name: "abc", position: "xyz")
let emp = Employee(number: "124")
let emp = Employee(name: "abc", number: "124")
答案 1 :(得分:1)
我假设您正在创建空的User对象,以便以后可以填写信息。我可以看到两个问题:一个,对象属性都必须是变量,而第二个,因为对象很容易犯错并传递错误的信息并不总是对应于真实实体。
更好的方法是定义一组参数,这些参数对于要定义的User对象是必需的,并让所有其他参数为可选参数,或为它们提供默认值。例如,如果我们选择用户名和电子邮件为必填项,并且让个人资料图片为可选,并且isVerified的默认值为false:
class User {
var userName: String
var email: String
var isVerified: Bool
var profileImageURL: String?
init(userName: String, email: String, isVerified: Bool = false) {
self.userName = userName
self.email = email
self.isVerified = isVerified
}
}