Ios 消除强制展开的最佳方法

Ios 消除强制展开的最佳方法,ios,swift,optional,forceunwrap,Ios,Swift,Optional,Forceunwrap,如何移除强制展开?第一个可以使用if let(或者guard let)处理的方法: 在第二个示例中,我将使用默认值: if let recorder = recorder { // here it is unwrapped } else { // handle nil case } 但是,我看到您已经在第二种情况下使用了if let,因此您不需要它。因此,我认为最好使用,如果让这两种情况都使用,那么可能是这样的: if (recorder?.isRunning() ?? fal

如何移除强制展开?

第一个可以使用
if let
(或者
guard let
)处理的方法:

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

if let recorder = recorder {
    // here it is unwrapped
} else {
    // handle nil case
}
但是,我看到您已经在第二种情况下使用了
if let
,因此您不需要它。因此,我认为最好使用
,如果让这两种情况都使用
,那么可能是这样的:

if (recorder?.isRunning() ?? false) {
    // ...
}
或者,正如@Fogmaster所指出的,在第二种方法中使用
guard
,看起来会更好一些:

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
            })
        })
    }
}

你可以把
recorder
改为懒惰

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
        })
    })
}

我会将第二个函数更改为使用
guard
,而不是
if
。有助于减少压痕,使外观更美观。
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
        })
    })
}
var recorder: Recorder = {
    return Recorder()
}()