我正在尝试为类创建一个可用的初始化程序.我的类将使用来自网络请求的输入进行初始化.网络不可靠,我想创建一个初始化器,检查所有属性上的存在,否则它将失败.
我试图在这里使用守卫,所以请随时指出方法中的任何明显的错误:
public class JobModel { let jobId: String let status: String let toName: String let toAddress: String let description: String let fee: Int let jobDate: NSDate let fromName: String let fromAddress: String init?(job: [String:AnyObject]) throws { guard self.jobId = job["jobid"] as! String else { throw InitializationError.MissingJobId } } }
守卫self.jobId行无法编译,错误:
对成员’下标’的模糊引用
关于如何纠正这个错误的任何想法?
解决方法
警卫需要符合BooleanType的条件.简单的作业没有.你需要这样的东西.
guard let j = job["jobid"] as? String else { throw InitializationError.MissingJobId } self.jobId = j
但是,您将收到错误“一个类实例的所有存储属性必须在从初始化程序抛出之前初始化”.这是预期和记录在Swift编程语言:
For classes,however,a failable initializer can trigger an
initialization failure only after all stored properties introduced by
that class have been set to an initial value and any initializer
delegation has taken place.
克里斯·拉特纳提到目前的行为是不合需要的:http://swift-language.2336117.n4.nabble.com/Swift-2-throwing-in-initializers-td439.html