swift - 快速简化功能

标签 swift function dictionary simplify

新手提醒。

我想在多页照片上使用相同的代码(以帮助我儿子认人)。因此,我没有重新插入每个人的名字,而是创建了 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)
}

关于swift - 快速简化功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48234406/

相关文章:

php - 使用PHP在mysql中插入数据时返回最后一个id

arrays - Swift 如何按键值对数组字典进行排序

swift - 快速和身份验证挑战中的 SSL Pinning

arrays - 无法将变体数组分配给类型化数组

jquery - 使用 jQuery 检测 iPhone 滑动

python - 使用python map等功能工具

c++ - 计算一个词在 map 中出现的次数 - 使用 transform() - 调用不匹配

iOS Swift - 删除 tableViewCell 中 tableview 中的行

ios - 核心数据崩溃获取

swift - AVAudioSourceNode 在快速 Playground 中不起作用