简化 swift 中的函数

simplifying a function in swift

新手提醒。

我想在多页照片上使用相同的代码(以帮助我儿子认人)。因此,我没有重新插入每个人的名字,而是创建了 appearingInPhoto(字典),这样我就可以使用 .a .b .c,而不必重命名每一行代码。

有没有办法进一步简化代码。所以我可以有一个代码来检查,如果按下按钮(检查 sender.currentTitle 是否等于任何字典值,如果是,运行 此代码:

print("pressed \(appearingInPhoto.a)")
        label.text = appearingInPhoto.a
        soundName = appearingInPhoto.a

现在这是完整的功能。

  var appearingInPhoto = (a:"omar", b:"john", c:"thomas")

  @IBAction func buttonPressed(_ sender: UIButton) {
    var soundName: String? = nil
    if sender.currentTitle == appearingInPhoto.a {
        print("pressed \(appearingInPhoto.a)")
        label.text = appearingInPhoto.a
        soundName = appearingInPhoto.a
    }else if sender.currentTitle == appearingInPhoto.b {
        print("pressed \(appearingInPhoto.b)")
        label.text = appearingInPhoto.b
        soundName = appearingInPhoto.b
    }else if sender.currentTitle == appearingInPhoto.c {
        print("pressed \(appearingInPhoto.c)")
        label.text = appearingInPhoto.c
        soundName = appearingInPhoto.c
    }
    if let soundName = soundName {
        playSoundFile(soundName)
    }
  }

提前致谢。

您可以只使用 ArraySet,以及 contains(_:):

let photoSubjects: Set = ["omar", "john", "thomas")

@IBAction func buttonPressed(_ sender: UIButton) {
    let title = sender.currentTitle

    guard photoSubjects.contains(title) else { return }

    print("pressed \(title)")
    label.text = title
    let soundName = title
    playSoundFile(soundName)
}