斯威夫特 3 随机化指数



我正在尝试用我的目录内容随机填充UITableView。

import UIKit
import AVFoundation
var songs:[String] = []
var audioPlayer = AVAudioPlayer()
var thisSong = 0
var audioStuffed = false
class FirstViewController: UIViewController, UITableViewDelegate,    UITableViewDataSource {
    @IBOutlet weak var myTableView: UITableView!
    func tableView(_ tableView: UITableView, numberOfRowsInSection  section: Int) -> Int {
        return songs.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        cell.textLabel?.text = songs[indexPath.row]
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        do
        {
            let audioPath = Bundle.main.path(forResource: songs[indexPath.row], ofType: ".mp3")
            try audioPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
            audioPlayer.play()
            thisSong = indexPath.row
            audioStuffed = true
        }
        catch
        {
            print ("ERROR")
        }
    }

你想洗牌你的歌曲数组吗?你可以使用这个(https://github.com/SwifterSwift/SwifterSwift/blob/master/Sources/Extensions/SwiftStdlib/ArrayExtensions.swift(

public mutating func shuffle() {
    // http://stackoverflow.com/questions/37843647/shuffle-array-swift-3
    guard count > 1 else { return }
    for index in startIndex..<endIndex - 1 {
        let randomIndex = Int(arc4random_uniform(UInt32(endIndex - index))) + index
        if index != randomIndex { swapAt(index, randomIndex) }
    }
}

首先你需要随机数组,你可以使用随机数组 -

override func viewDidLoad() {
   super.viewDidLoad()
   songs.shuffle()
}
extension Array {
    mutating func shuffle() {
        for _ in 0..<self.count {
            sort { (_,_) in arc4random() < arc4random() }
        }
    }
}

最新更新