我正在尝试重构结构的 init 方法。 Init 接收字典并从中初始化结构。有几个很长的解析逻辑部分(遍历数组等)并且 init 太长了。我试图提取这个逻辑来分离函数(新的 Xcode 重构功能的荣誉!)但是编译器告诉我:
self
used before all stored properties are initialized
有什么方法可以重构我凌乱的 init 吗?
我想到了创建单独的 Parser
类,但是模型的 res(非常大的项目)在每个结构 init
中解析 JSON。所以创建这个Parser
类会使项目不一致...
示例代码:
struct Example {
let intParam: Int
let dates: [Date]
// Current implementation
init(dictionary: [String: Any]) {
self.intParam = dictionary["intParam"] as? Int ?? 0
var dates: [Date] = []
// long parsing here
self.dates = dates
}
// Desired implementation
init(dictionary: [String: Any]) {
self.intParam = dictionary["intParam"] as? Int ?? 0
self.dates = parseDates(dictionary)
}
private func parseDates(_ dictionary: [String: Any]) -> [Date] {
var dates: [Date] = []
// long parsing here
return dates
}
}
最佳答案
尝试使 parseDates
成为静态函数。
// Desired implementation
init(dictionary: [String: Any]) {
self.intParam = dictionary["intParam"] as? Int ?? 0
self.dates = Example.parseDates(dictionary)
}
private static func parseDates(_ dictionary: [String: Any]) -> [Date] {
var dates: [Date] = []
// long parsing here
return dates
}
关于swift - 从 struct init 中提取函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45887907/