从结构初始化提取函数
我试图重构struct的init方法。 Init接收字典并从中初始化结构。有几个长的解析逻辑部分(遍历数组等)和init太长。我试图提取这种逻辑功能分开,但是编译器告诉我(荣誉新的Xcode的重构功能!):从结构初始化提取函数
self
使用的所有存储属性初始化之前
有什么办法来重构我的凌乱初始? 我想到了创建单独的Parser
类的想法,但模型的res(真的很大的项目)解析了每个结构中的JSON init
。因此,创建这个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
}
你想要做什么,似乎非常奇怪,但是这将让你的“理想的实现”:
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
}
不过,我看不出有什么你觉得这让你。如果这个解析操作在其他任何地方都不需要,并且你只是希望它看起来整洁,为什么不使用本地函数呢?
init(dictionary: [String: Any]) {
self.intParam = dictionary["intParam"] as? Int ?? 0
func parseDates(_ dictionary: [String: Any]) -> [Date] {
var dates: [Date] = []
// long parsing here
return dates
}
self.dates = parseDates(dictionary)
}
你能告诉我为什么你认为这是一个奇怪的解决方案?这是一个示例代码。真正的初始化大小现在是100多行,所以我试图让它更易读... – OgreSwamp
我不明白为什么它会变得更具可读性,只是因为代码被分解为一种方法。如果这是一次性代码,那么它就没有可读性,因为它是误导性的。这就是为什么我建议使用本地功能。现在_that_更具可读性! – matt
谢谢。在你的第一个代码中,所有的属性赋值都是紧凑的,并且遵循对方。它很容易阅读。在第二个代码中,您将在每个属性分配之间分配代码块。我看不出第二个建议的解决方案如何使它更具可读性,只有普通的100多行代码没有本地功能。我不认为函数只能在代码被重用的情况下使用。我认为代码分离到逻辑和平也是正确的功能用法。为了减少第一个解决方案的误导,你可以添加'fileprivate',这样就很明显这个静态方法从来不会在这个文件之外调用。 – OgreSwamp
您的代码没有意义,且您的结果无法复制。你说你在所有存储的属性初始化之前得到“自我使用”,但我没有;我们从来没有达到那个地步,因为'dictionary [“intParam”] ?? 0'不编译。 – matt
你可以使功能静态 – dan
此外,这个问题本身似乎没有任何意义。你不能有一个'[String:Int]'的字典,它也是'[String:Date]'的字典。我没有看到你认为你要这样做的地方。 – matt