Helping the type checker


(Daniel Müllenborn) #1

I have recently used the "-warn-long-function-bodies" flag, and have luckily only one place in my code where I should give the compiler a better hint. At Swift 4 it looks a bit different, but I prefer to wait before I make any unnecessary changes.

The code is as follows:

  subscript(path: IndexPath) -> ViewModel.SubField {
    get {
      return ViewModel.connectors[path[0]][path[1]].connector.subFields[path[2]][path[3]]
    }
    set {
      ViewModel.connectors[path[0]][path[1]].subFields[path[2]][path[3]] = newValue
    }
  }

I made it:

  subscript(path: IndexPath) -> ViewModel.SubField {
    get {
      let connector = ViewModel.connectors[path[0]][path[1]]
      return connector.subFields[path[2]][path[3]]
    }
    set {
      ViewModel.connectors[path[0]][path[1]].subFields[path[2]][path[3]] = newValue
    }
  }

And the warning for the get disappears, but I do not know what to do with set part.
The 1.4 seconds it takes, now bother me where I know it.

For a better understanding, the types look like this.

enum ViewModel {
  
  struct Connector {
    var subFields: [[SubField]] = []
  }
  
  static var connectors: [[ViewModel.Connector]] = []
  
  struct SubField: Hashable {}
  
}

Has anyone a solution for me?

Regards,
Daniel