我正在尝试为一个类创建一个失败的初始化器.我的课程将使用网络请求中的输入进行初始化.网络不可靠,我想创建一个初始化程序来检查所有属性的存在,否则将失败.
I am trying to create a failable initializer for a class. My class will be initialized using input from a network request. Networks being unreliable, I want to create an initializer the checks for the presence on all properties, and for it to fail otherwise.
我在这里尝试使用警惕,所以请随时指出该方法中的任何明显错误:
I am trying to make use of guard here, so please feel free to point any obvious mistakes in the approach:
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 } } }guard self.jobId行无法编译,出现错误: Ambiguous reference to member 'subscript'
The guard self.jobId line is failing to compile, with error: Ambiguous reference to member 'subscript'
关于如何纠正此错误的任何想法?
Any ideas on how to correct this error?
推荐答案guard需要符合BooleanType的条件.简单分配不是.您将需要这样的东西.
guard requires a condition that conforms to BooleanType. Simple assignment doesn't. You would need something like this.
guard let j = job["jobid"] as? String else { throw InitializationError.MissingJobId } self.jobId = j但是,您将收到错误消息:从实例化器抛出类之前,必须先初始化类实例的所有存储属性".这是预期的,并在The Swift Programming Language中进行了记录:
However, then you'll get the error "all stored properties of a class instance must be initialized before throwing from an initializer." This is expected and documented in the The Swift Programming Language:
但是,对于类,失败的初始化程序可能会触发 只有在由引入的所有存储属性之后,初始化失败 该类已被设置为初始值和任何初始化程序 委派了.
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.
克里斯·拉特纳(Chris Lattner)在此处提到当前行为是不受欢迎的: http ://swift-language.2336117.n4.nabble/Swift-2-throwing-in-initializers-td439.html
Chris Lattner mentions the current behavior is undesirable here: swift-language.2336117.n4.nabble/Swift-2-throwing-in-initializers-td439.html
更多推荐
在字典上对成员“下标"的引用含糊不清
发布评论