消除力量展开的最佳方法

问题描述 投票:-1回答:2
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
                })
            })
        }
    }
}

我们如何解除力量打开?

ios swift optional forceunwrap
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
        })
    })
}

1
投票

你可以让recorder懒惰。

var recorder: Recorder = {
    return Recorder()
}()
© www.soinside.com 2019 - 2024. All rights reserved.