Home > Software engineering >  Swift Cannot find variable in scope
Swift Cannot find variable in scope

Time:06-06

Swift giving error that var is not in scope. "Cannot find 'midiManager' in scope" I am not sure how to fix issue

menu.swift

struct MainMenuBar: MenuBar {
    public var body: StandardMenuBar {
        StandardMenu(title: "Midi Devices") {
            midiManager.endpoints.outputs.forEach { device in
                TextMenuItem(title: device.name) { _ in
                    print(device.uniqueID)
                }
            }
        }
    }
}

midi.swift

@objc(ReactNativeMidiModule)
class ReactNativeMidiModule: RCTEventEmitter, NSApplicationDelegate {
  // Create midi manager
  public let midiManager = MIDI.IO.Manager(
    clientName: "MIDIEventLogger",
    model: "ELMC Midi Monitor",
    manufacturer: "ELMC")

  // other code
}

enter image description here

CodePudding user response:

midiManager is not present inside your MainMenueBar. So midiManager can not be found. You must need to add midiManager inside your MainMenueBar structure. Like this -

struct MainMenuBar: MenuBar
{
    public let midiManager = MIDI.IO.Manager(clientName: "MIDIEventLogger", model: "ELMC Midi Monitor", manufacturer: "ELMC")
    public var body: StandardMenuBar
    {
        
        StandardMenu(title: "Midi Devices")
        {
            midiManager.endpoints.outputs.forEach { device in
                TextMenuItem(title: device.name) { _ in
                    print(device.uniqueID)
                }
            }
        }
    }
}

or By creating a common class as-

class MidiManager {
    static let midiManager = MIDI.IO.Manager(clientName: "MIDIEventLogger", model: "ELMC Midi Monitor", manufacturer: "ELMC")
}

And then use it in both MainMenuBar and ReactNativeMidiModule as-

struct MainMenuBar: MenuBar {
    public let midiManager = MidiManager.midiManager
    public var body: StandardMenuBar {
        StandardMenu(title: "Midi Devices") {
            midiManager.endpoints.outputs.forEach { device in
                TextMenuItem(title: device.name) { _ in
                    print(device.uniqueID)
                }
            }
        }
    }
}

@objc(ReactNativeMidiModule)
class ReactNativeMidiModule: RCTEventEmitter, NSApplicationDelegate {
  // Create midi manager
  public let midiManager = MidiManager.midiManager

  // other code
}
  • Related