从 struct init 中提取函数

Ogr*_*amp 0 struct initialization swift

我正在尝试重构 struct 的 init 方法。Init 接收字典并从中初始化结构。有几个长解析逻辑部分(遍历数组等),init 太长。我试图提取这个逻辑来分离函数(对新的 Xcode 重构功能赞不绝口!)但编译器告诉我:

self 在初始化所有存储的属性之前使用

有什么方法可以重构我凌乱的 init 吗?我开始想到创建单独的Parser类,但模型的 res(非常大的项目)在每个 struct 中解析 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
    }
}
Run Code Online (Sandbox Code Playgroud)

bhz*_*zag 5

尝试制作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
   }
Run Code Online (Sandbox Code Playgroud)