Swift Error: Struct 'XX' must be completely initialized before a member is stored to

Swift Error: Struct 'XX' must be completely initialized before a member is stored to

我正在尝试在 Swift 中定义 AudioStreamBasicDescription。

在Objective-C中,我使用了类似下面的代码。

AudioStreamBasicDescription ASBD;
ASBD.mSampleRate            = 8000;
ASBD.mFormatID              = kAudioFormatLinearPCM;
ASBD.mFormatFlags           = kAudioFormatFlagsCanonical | kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
ASBD.mFramesPerPacket       = 1;
ASBD.mChannelsPerFrame      = 1;
ASBD.mBitsPerChannel        = 16;
ASBD.mBytesPerPacket        = 2;
ASBD.mBytesPerFrame         = 2;

我转换后的 Swift 代码如下

var ASBD: AudioStreamBasicDescription
ASBD.mSampleRate = 8000  // ERROR here
ASBD.mFormatID = kAudioFormatLinearPCM
ASBD.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked
ASBD.mFramesPerPacket = 1
ASBD.mChannelsPerFrame = 1
ASBD.mBitsPerChannel = 16
ASBD.mBytesPerPacket = 2
ASBD.mBytesPerFrame = 2

但是 swift 代码的第二行抛出了这个错误。我不知道为什么会收到此错误。谁能帮我解决这个问题?

这意味着一个结构在使用之前需要完全初始化。 AudioStreamBasicDescription是一个结构体,使用前需要先初始化。正确的代码如下:

var ASBD: AudioStreamBasicDescription! = AudioStreamBasicDescription()
ASBD.mSampleRate = 8000
ASBD.mFormatID = kAudioFormatLinearPCM
ASBD.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked
ASBD.mFramesPerPacket = 1
ASBD.mChannelsPerFrame = 1
ASBD.mBitsPerChannel = 16
ASBD.mBytesPerPacket = 2
ASBD.mBytesPerFrame = 2