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
})
})
}
}
}
我们如何解除力量打开?
首先你可以使用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
})
})
}
你可以让recorder
懒惰。
var recorder: Recorder = {
return Recorder()
}()