Home > Software design >  Swift how to refactor code to use inline conditions
Swift how to refactor code to use inline conditions

Time:07-20

I am trying to refactor this block of swift code. toOuputs, mode, and filter are my targets areas I am looking to refactor. Is there a way that I can clean this up a little

func start(_ selectedDevice: Int32, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
    do {
        print("Starting MIDI manager.")
        try midiManager.start()
        
        let inputTag = "InputConnection1"
        try midiManager.addInputConnection(
            toOutputs: selectedDevice == 0 || (1 != 0) ? [] : [.uniqueID(selectedDevice)],
            tag: inputTag,
            mode: selectedDevice == 1 ? .allEndpoints : .definedEndpoints,
            filter: selectedDevice == 1 ? .owned() : .default()
        )
        resolve("Started!")
    } catch {
      reject("400", "Setup Error:", error)
    }
  }

CodePudding user response:

You could move the values to variables.

func start(_ selectedDevice: Int32, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
    do {
        print("Starting MIDI manager.")
        try midiManager.start()
        
        let inputTag = "InputConnection1"

        let toOutputs: [Output] = selectedDevice == 0 || (1 != 0) ? [] : [.uniqueID(selectedDevice)]

        let mode: Mode = selectedDevice == 1 ? .allEndpoints : .definedEndpoints

        let filter: Filter = selectedDevice == 1 ? .owned() : .default()

        try midiManager.addInputConnection(
            toOutputs: toOutputs,
            tag: inputTag,
            mode: mode,
            filter: 
        )
        resolve("Started!")
    } catch {
        reject("400", "Setup Error:", error)
    }
}

You will need to replace the types Output, Mode, and Filter with the correct type.

  • Related