在 swift 中声明变量时可以使用通配符吗?

Can you use wildcards when declaring variables in swift?

我正在通过构建 Soundboard 应用程序来学习编码。在稍微改变曲调后,我正在使用 audioEngine 播放一些声音。在我的 viewDidLoad 中,我声明我的 variables:

var audioFile1 = AVAudioFile()
var audioFile2 = AVAudioFile()

if let filePath = Bundle.main.path(forResource: "PeteNope", ofType:
        "mp3") {
        let filePathURL = URL(fileURLWithPath: filePath)

        setPlayerFile(filePathURL)

    }
if let filePath2 = Bundle.main.path(forResource: "Law_WOW", ofType:
        "mp3") {
        let filePath2URL = URL(fileURLWithPath: filePath2)

        setPlayerFile2(filePath2URL)

    }
func setPlayerFile(_ fileURL: URL) {
    do {
        let file1 = try AVAudioFile(forReading: fileURL)

        self.audioFile1 = file1


    } catch {
        fatalError("Could not create AVAudioFile instance. error: \(error).")
    }
}

func setPlayerFile2(_ fileURL: URL) {
    do {
        let file2 = try AVAudioFile(forReading: fileURL)

        self.audioFile2 = file2


    } catch {
        fatalError("Could not create AVAudioFile instance. error: \(error).")
    }
}

然后我按如下方式连接 nodes

audioEngine.attach(pitchPlayer)
audioEngine.attach(timePitch)
audioEngine.connect(pitchPlayer, to: timePitch, format: audioFile1.processingFormat)
audioEngine.connect(timePitch, to: audioEngine.outputNode, format: audioFile1.processingFormat)
audioEngine.connect(pitchPlayer, to: timePitch, format: audioFile2.processingFormat)
audioEngine.connect(timePitch, to: audioEngine.outputNode, format: audioFile2.processingFormat) 

所以,我的问题是,由于变量除了数字之外是相同的,有没有办法以编程方式编写它,这样我就不必单独声明 nodes

据我了解你的问题,你有很多这样的资源 "PeterNope" 和 "Law_WOW" 并想快速将它们添加为节点。

您的代码可以重构如下,以添加您想要的资源:

var resources = ["PeterNope", "Law_WOW", "otherResource1", "otherResource2", ...]

func setPlayerFile(_ fileName: String) {
    // make sure resource exists and break if not.
    guard let filePath = Bundle.main.path(forResource: fileName, ofType: "mp3") else {
        print ("resource file \(fileName) does not exist")            
        return
    }

    let fileURL = URL(fileURLWithPath: filePath)

    // open file from resource
    do {
        let file = try AVAudioFile(forReading: fileURL)
    } catch {
        fatalError("Could not create AVAudioFile instance. error: \(error).")
    }

    // connect nodes
    connect(pitchPlayer, to: timePitch, format: file.processingFormat)
    audioEngine.connect(timePitch, to: audioEngine.outputNode, format: file.processingFormat)
}

// connect all resources
attach(pitchPlayer)
audioEngine.attach(timePitch)

for index in 0..(resources.count - 1) {
    setPlayer(resources[index]
}

// or quicker and swiftier:
resources.forEach { setPlayerFile([=10=]) }

我建议阅读一般的 for 循环和控制流:https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html