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

时间:2019-03-14 16:57:05

标签: ios arrays random

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

我当前使用的设置将为“ VowelFaceXX” IBOutlets返回随机标题,但通常会重复结果。我希望每个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)
}


}

1 个答案:

答案 0 :(得分:0)

按照@vadian的建议,洗牌gb[\[Mu]_, p95_] := Block[{p = Min[p95/\[Mu], 5.8]}, \[Mu] FindRoot[CDF[GammaDistribution[1/\[Beta], \[Beta]], p] - .95 == 0, {\[Beta], 1, If[p == 1, 1.1, p]}][[1, 2]]];

vowelArray

let vowelFaces = [vowelFace01, vowelFace02, vowelFace03, vowelFace04, vowelFace05] for (vowelFace, vowel) in zip(vowelFaces, vowelArray.shuffled()) { vowelFace?.setTitle(vowel, for: .normal) } 允许您枚举一对序列,并以最短的长度停止,在这种情况下非常方便。