swift - 从 struct init 中提取函数

标签 swift struct initialization

我正在尝试重构结构的 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/

相关文章:

ios - 更改 UIToolbar 项目导致工具栏变为空白

c - 使用指向结构的指针或引用

C编程数据输入错误

c++ - 为什么就地成员初始化在 C++11 中使用复制构造函数?

arrays - 如何生成数字序列

c - PowerPC 编译器的结构体数组

ios - 我应该使用 KVO 还是 NSNotificationCenter?

SwiftUI:支持多种模式

ios - 更改某些实体中某些属性的类型后如何迁移核心数据模型?

c - C 中的结构中的字符串