-1
var recorder : Recorder? = nil

func startAudioRecording() {
    if recorder == nil {
        recorder = Recorder()
    }
    if !recorder!.isRunning() {
        recorder?.startRecording({ [weak self] audioData in
            self?.remoteInterface?.sendVoice(audioData.0)
        }, withCompletionBlock: { (_) in })
    }
}

func stopAudioRecording(_ keyCommand: String!){
    if let _ = recorder {
        if(recorder?.isRunning())! {
            recorder?.stopRecording(completionBlock: { (isFinished: Bool) in
                DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + Double(Int64(1 * NSEC_PER_MSEC)) / Double(NSEC_PER_SEC), execute: { [unowned self] in
                    self.remoteInterface?.sendTouchUp(keyCommand)
                    self.audioRecorder = nil
                })
            })
        }
    }
}

我们如何消除强制展开?

4

2 回答 2

5

if let您可以使用(或替代)处理的第一个guard let

if let recorder = recorder {
    // here it is unwrapped
} else {
    // handle nil case
}

在第二个中,我将使用默认值:

if (recorder?.isRunning() ?? false) {
    // ...
}

但是,我看到您已经if let在第二种情况下使用了,所以您不需要它。所以我认为if let在这两种情况下都是最好的,所以可能是这样的:

var recorder : Recorder? = nil

func startAudioRecording(){
    if recorder == nil {
        recorder = Recorder()
    }
    if let recorder = recorder,
        !recorder.isRunning() {

        recorder.startRecording({ [weak self] audioData in
            self?.remoteInterface?.sendVoice(audioData.0)
        }, withCompletionBlock: { (_) in })
    }
}

func stopAudioRecording(_ keyCommand: String!){
    if let recorder = recorder,
        recorder.isRunning() {

        recorder.stopRecording(completionBlock: { (isFinished: Bool) in
            DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + Double(Int64(1 * NSEC_PER_MSEC)) / Double(NSEC_PER_SEC), execute: { [unowned self] in
                self.remoteInterface?.sendTouchUp(keyCommand)
                self.audioRecorder = nil
            })
        })
    }
}

或者,正如@Fogmaster 所指出的,guard在第二种方法中使用可能看起来更好一些:

func stopAudioRecording(_ keyCommand: String!){
    guard let recorder = recorder,
        recorder.isRunning() else {
        return
    }

    recorder.stopRecording(completionBlock: { (isFinished: Bool) in
        DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + Double(Int64(1 * NSEC_PER_MSEC)) / Double(NSEC_PER_SEC), execute: { [unowned self] in
            self.remoteInterface?.sendTouchUp(keyCommand)
            self.audioRecorder = nil
        })
    })
}
于 2018-01-22T09:54:38.053 回答
1

你可以只是recorder懒惰。

var recorder: Recorder = {
    return Recorder()
}()
于 2018-01-22T11:30:02.937 回答