[英]Swift Playground didn't recognize structs in other folders
我在 Swift Playground 中使用 AVFoundation 的 AVAudioEngine 和 SwiftUI 並使用 MVVM 作為架構。 但是如果我在文件中分離我的結構,我會收到兩個錯誤:執行被中斷,原因:信號 SIGABRT。 在 scope 中找不到文件。 唯一可行的方法是在同一個文件中使用它們。
這是 Playground 的基本代碼,我稱之為 MusicCreatorView。
import SwiftUI
import PlaygroundSupport
public struct StartView: View {
public var body: some View {
ZStack {
Rectangle()
.fill(Color.white)
.frame(width: 400, height: 400, alignment: .center)
NavigationView {
VStack {
NavigationLink("Start", destination: MusicCreatorView())
}
}
}
}
}
PlaygroundPage.current.setLiveView(StartView()) // error: Execution was interrupted, reason: signal SIGABRT.
AudioEngine 可以通過 StartView 找到(如果在 StartView 調用,只需將 SIGABRT 錯誤從 PlaygroundPage.current.setLineView() 移動到調用它的位置)但 MusicCreatorView 找不到。
import Foundation
import AVFoundation
public struct AudioEngine {
public var engine = AVAudioEngine()
public var player = AVAudioPlayerNode()
public var audioBuffer: AVAudioPCMBuffer?
public var audioFormat: AVAudioFormat?
public var audioFile: AVAudioFile? {
didSet {
if let audioFile = audioFile {
audioFormat = audioFile.fileFormat
}
}
}
public var audioFileURL: URL? {
didSet {
if let audioFileURL = audioFileURL {
audioFile = try? AVAudioFile(forReading: audioFileURL)
}
}
}
public init() {
setupAudio()
}
public mutating func setupAudio() {
audioFileURL = Bundle.main.url(forResource: "EverybodysCirculation", withExtension: "mp3")
guard let format = audioFormat else { return }
engine.attach(player)
engine.connect(player, to: engine.mainMixerNode, format: format)
engine.prepare()
do {
try engine.start()
} catch {
print(error.localizedDescription)
}
}
public func scheduleAudioFile() {
guard let audioFile = audioFile else { return }
player.scheduleFile(audioFile, at: nil, completionHandler: nil)
}
public func playSound() {
player.isPlaying ? player.pause() : player.play()
}
}
嘗試在 MusicCreatorView 調用 AudioEngine
import Foundation
import SwiftUI
import AVFoundation
public struct MusicCreatorView: View {
var audioEngine = AudioEngine() // Cannot find 'AudioEngine' in scope
public init() {}
public var body: some View {
Text("Try to Create your own music")
Button("play") {
print("apertou")
audioEngine.playSound() // audioEngine <<error type>>
}
}
}
Sources 中的多個文件不能互相看到。 它們只是可供實際操場使用的獨立庫。 您應該在真正的 iOS 項目中開發它,而不是在操場上。
您只需要明確聲明內容為公開。 這很煩人,有時我需要關閉並重新打開操場,以便在將它們標記為公開后生效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.