在swift中简化函数

时间:2018-01-12 21:44:17

标签: swift function dictionary simplify

新手警报。

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

有没有办法进一步简化代码。所以我可以只有一个代码检查,如果Button按下(检查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)
    }
  }

提前谢谢你。

1 个答案:

答案 0 :(得分:2)

您可以使用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)
}