gpt4 book ai didi

ios - 从数组中返回一个没有重复数字的随机元素(Swift 4.2)

转载 作者:行者123 更新时间:2023-11-29 05:55:54 30 4
gpt4 key购买 nike

我试图从数组中返回没有重复结果的随机元素,但我无法找到使用新 RandomKit 的 Swift 4.2 解决方案。

我当前的设置将返回“VowelFaceXX”IBOutlet 的随机标题,但经常会重复结果。我希望每个 IBOutlet 都有独特的结果。

我还希望以后能够在数组中包含超过 5 个元素,但保留 5 个 IBOutlet。

我已经发布了以下代码:

import UIKit
import AVFoundation

class VowelsVC: UIViewController {


var audioPlayer : AVAudioPlayer?
var selectedSoundFileName : String = ""
var randomVowelIndex : Int = 0
var vowelArray = ["A", "E", "I", "O", "U"]


@IBOutlet weak var vowelFace01: UIButton!
@IBOutlet weak var vowelFace02: UIButton!
@IBOutlet weak var vowelFace03: UIButton!
@IBOutlet weak var vowelFace04: UIButton!
@IBOutlet weak var vowelFace05: UIButton!


func randomVowel() {
randomVowelIndex = Int.random(in: 0 ... 4)
}


func playAudio() {
let path = Bundle.main.path(forResource: selectedSoundFileName, ofType:nil)!
let url = URL(fileURLWithPath: path)

do {
audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer?.play()
} catch {
print("Couldn't load audio") }
}


@IBAction func dismissVowelVC(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}


override func viewDidLoad() {
super.viewDidLoad()

randomVowel()
selectedSoundFileName = "WhichOneIs.mp3"

playAudio()

let when = DispatchTime.now() + 1.7
DispatchQueue.main.asyncAfter(deadline: when) {
self.selectedSoundFileName = self.vowelArray[self.randomVowelIndex]+".mp3"
self.playAudio()

}

randomVowel()
vowelFace01.setTitle("\(vowelArray[randomVowelIndex])", for: .normal)
randomVowel()
vowelFace02.setTitle("\(vowelArray[randomVowelIndex])", for: .normal)
randomVowel()
vowelFace03.setTitle("\(vowelArray[randomVowelIndex])", for: .normal)
randomVowel()
vowelFace04.setTitle("\(vowelArray[randomVowelIndex])", for: .normal)
randomVowel()
vowelFace05.setTitle("\(vowelArray[randomVowelIndex])", for: .normal)
}


}

最佳答案

按照 @vadian 的建议,随机播放 vowelArray

let vowelFaces = [vowelFace01, vowelFace02, vowelFace03, vowelFace04, vowelFace05]
for (vowelFace, vowel) in zip(vowelFaces, vowelArray.shuffled()) {
vowelFace?.setTitle(vowel, for: .normal)
}

zip 允许您枚举一对序列,在最短长度处停止,这在这种情况下非常方便。

关于ios - 从数组中返回一个没有重复数字的随机元素(Swift 4.2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55168168/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com