Search code examples
swiftunwrap

How to unwrap UInt32? in Swift?


I'm struggling with something very simple, and I have no idea what's going on. By the way, it's Swift 1.2, but I don't think it's a special case!

I have a UInt32? variable, and I need to get the value, but using ! throws an error: fatal error: unexpectedly found nil while unwrapping an Optional value. And no, I know this is not nil.

static func checkBitrate(filePath: String) -> Bool {

    let audioURL = NSURL.fileURLWithPath(filePath)
    var audioFile : AudioFileID = nil
    var theErr: OSStatus? = nil
    let hint: AudioFileTypeID = 0
    theErr = AudioFileOpenURL(audioURL, Int8(kAudioFileReadPermission), hint, &audioFile)

    if (theErr != OSStatus(noErr)) {
        return false
    }

    var outDataSize: UInt32 = 0
    var isWritable: UInt32 = 0
    theErr = AudioFileGetPropertyInfo(audioFile, UInt32(kAudioFilePropertyBitRate), &outDataSize, &isWritable)
    if (theErr != OSStatus(noErr)) {
        return false
    }

    var bitrate: UInt32? = nil
    theErr = AudioFileGetProperty(audioFile, UInt32(kAudioFilePropertyBitRate), &outDataSize, &bitrate)
    if (theErr != OSStatus(noErr)) {
        return false
    }

    println("Bitrate value: \(bitrate)")

    let br = bitrate!
    //return br == 192000
    return false
}

The error is thrown at line let br = bitrate!.

error with value in debugger

I am a bit lost, what do I do wrong?


Solution

  • You just need to initialize your var

     var bitrate: UInt32 = 0