使用阵列中的手电筒执行摩尔斯电码

Executing morse code with flashlight from array

我有一个字符数组“.”和“-”这是莫尔斯电码的翻译文本。由于莫尔斯电码,它们当然是按照明确指定的顺序排列的。现在我想在点击按钮后将此数组转换为 iPhone 中手电筒的长闪和短闪。我当然尝试用 'if' 语句循环遍历这个数组,就像下面的 scheduledTimers 一样,但显然没有成功,循环立即执行并且手电筒只启动一次。

let dash: Character = "-"
let dot: Character = "."

for i in translatedArray {
  if i == dash{

    //two sec delay at the beggining because of the pause beetween each flash which is equal to one dot
    timer1 = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(toggleFlashlightOn), userInfo: nil, repeats: false)
    timer2 = Timer.scheduledTimer(timeInterval: 6, target: self, selector: #selector(toggleFlashlightOff), userInfo: nil, repeats: false)
    print("long flash activated")
  }else if i == dot{
    timer1 = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(toggleFlashlightOn), userInfo: nil, repeats: false)
    timer2 = Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(toggleFlashlightOff), userInfo: nil, repeats: false)
    print("short flash activated")
  } else { return }
}

我还尝试使用 delay() 函数延迟单独的 'if' 迭代,但是使用莫尔斯电码执行此循环在每次迭代之间应该有不规则的时间间隔,具体取决于先前的字符,也就是先前的闪光长度,并且delay() 只有秒的静态值,所以这也没有用。

我终于在这里找到了 this 话题。除了将它更新为 swift4,并将莫尔斯电码字符数组更改为时间间隔数组,我成功地做到了这一点,这将是解决我的问题的完美方法……但它不起作用。它仅以一种打开的模式打开手电筒,并使用数组中的第一个时间间隔值定期刷新无休止地打印 "ON",例如每 2 秒左右。所以它永远不会关闭手电筒。

let shortFlash: Double = 2
let longFlash: Double = 4
let pause: Double = 2

var sequenceOfFlashes: [Double] = []

//this works ok, prints correct values in correct order from sequenceOfFlashes array

func setupMorseFlashesSequence(){  
    let dot: Character = "•"
    let line: Character = "—"

    for i in translatedArray { 
        switch i {
        case dot:
            sequenceOfFlashes.append(shortFlash)
            sequenceOfFlashes.append(pause)
        case line:
            sequenceOfFlashes.append(longFlash)
            sequenceOfFlashes.append(pause)
        default:
            return
        }
    }
    print(sequenceOfFlashes)
}

var index: Int = 0

weak var timer: Timer?

func scheduleTimer(){
    timer = Timer.scheduledTimer(timeInterval: sequenceOfFlashes[index], target: self, selector: #selector(timerTick), userInfo: nil, repeats: false)
}

 @objc func timerTick(){
    if index == sequenceOfFlashes.count {
        stop()
    }
    turnFlashlight(on: index % 2 == 0)
    scheduleTimer()
}

func start(){
    index = 0
    turnFlashlight(on: true)
    scheduleTimer()
}

func stop(){
    timer?.invalidate()
    turnFlashlight(on: false)
}

deinit{
    timer?.invalidate()
}

我怎样才能实现在不同的时间一个一个地执行这个闪烁?

您忘记在 timerTick() 中递增 index:

@objc func timerTick(){
    index += 1
    if index == sequenceOfFlashes.count {
        stop()
    }
    turnFlashlight(on: index % 2 == 0)
    scheduleTimer()
}