swift - Swift Playground 无法识别其他文件夹中的结构
问题描述
我在 Swift Playground 中使用 AVFoundation 的 AVAudioEngine 和 SwiftUI,并使用 MVVM 作为架构。但是如果我在文件中分离我的结构,我会收到两个错误:执行被中断,原因:信号 SIGABRT。并且在范围内找不到文件。唯一可行的方法是在同一个文件中使用它们。
这是 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>>
}
}
}
这是我的文件的组织方式 https://i.stack.imgur.com/losWf.png
解决方案
Sources 中的多个文件不能互相看到。它们只是可供实际操场使用的独立库。你应该在一个真正的 iOS 项目中开发它,而不是在操场上。
推荐阅读
- .htaccess - .htaccess 重写 https:// 前标记子域的条件
- node.js - 在 NestJS 中使用多个套接字适配器
- c++ - 遵循 Glynn 计算永久值的公式的矩阵乘法问题
- karate - karate-config.js 中是否可以有两个 baseUrls?
- sql - 如何在 Spark Scala 中将模式添加到另一个文件中的文件
- eclipse - 根文件属性
- javascript - Angular Unit Testing - 如何在初始化组件时修复“无法读取未定义的属性“middle_name””
- kubernetes - Error validating Pod template with NodeSelector
- c# - Add an inner or outer join based on a parameter
- jquery - Jquery 将值存储在 MouseOver 上的 2 个不同图标上