【发布时间】:2015-09-23 20:48:50
【问题描述】:
我有一种情况,我试图覆盖 NSError 以提供一个错误实例,我将多次重复使用。
在我更新 Xcode 并转换为 Swift 2 之前,我的代码一直在工作。
public class NAUnexpectedResponseTypeError: NSError {
public convenience init() {
let messasge = "The object fetched by AFNetworking was not of an expected type."
self.init(
domain: "MyDomain",
code: 6782,
userInfo: [NSLocalizedDescriptionKey: messasge]
)
}
}
编译器显示Cannot override 'init' which has been marked unavailable。我可以通过这样做来破解它:
public class NAUnexpectedResponseTypeError: NSError {
public class func error() -> NSError {
let message = "The object fetched by AFNetworking was not of an expected type."
return NAUnexpectedResponseTypeError(
domain: "MyDomain",
code: 6782,
userInfo: [NSLocalizedDescriptionKey: message]
)
}
}
所以,我的问题是:
- 有没有办法在这种情况下添加一个空的
init方法? - 如果 1 为“是”,出于某种原因,这是一个坏主意吗?
- 我使用类方法的解决方法是缓解此问题的适当方法吗?
编辑:
我想出了另一种解决方法,我更喜欢使用类方法的解决方法。我仍然不高兴我不能覆盖空的 init 方法。
public class NAUnexpectedResponseTypeError: NSError {
public convenience init(message: String?) {
var errorMessage: String
if let message = message {
errorMessage = message
} else {
errorMessage = "The object fetched by AFNetworking was not of an expected type."
}
self.init(
domain: "MyDomain",
code: 6782,
userInfo: [NSLocalizedDescriptionKey: errorMessage]
)
}
}
【问题讨论】:
-
除了此处显示的内容之外,您是否还向您的课程添加了更多代码?因为我想知道为什么子类是必要的。
-
@TomHarrington 你会建议类似 NSError 的扩展吗?