Swift:索引超出范围



我想从添加到xcode的文件夹中播放一些歌曲。

我使用选项卡式应用程序,代码是这样的:

func playThis(thisOne:String)
{
    do
    {
        let audioPath = Bundle.main.path(forResource: thisOne, ofType: ".mp3")
        try audioPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
        audioPlayer.play()
    }
    catch
    {
        print ("ERROR")
    }
}
override func viewDidLoad() {
    super.viewDidLoad()
    label.text = songs[thisSong] //error index out of range
}

但是当我运行时,这首歌不出现在第一次查看控制器,当我单击第二视图控制器选项卡应用程序崩溃时,原因是:

索引超出范围

第一个视图控制器代码是这样的:

import UIKit
import AVFoundation
var audioPlayer = AVAudioPlayer()
var songs:[String] = []
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: UITableViewCellStyle.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")
    }
}

第二视图控制器代码:

override func viewDidLoad()
{
    super.viewDidLoad()
    gettingSongNames()
}

override func didReceiveMemoryWarning()
{
    super.didReceiveMemoryWarning()
}

//FUNCTION THAT GETS THE NAME OF THE SONGS
func gettingSongNames()
{
    let folderURL = URL(fileURLWithPath:Bundle.main.resourcePath!)
    do
    {
        let songPath = try FileManager.default.contentsOfDirectory(at: folderURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
        //loop through the found urls
        for song in songPath
        {
            var mySong = song.absoluteString
            if mySong.contains(".mp3")
            {
                let findString = mySong.components(separatedBy: "/")
                mySong = findString[findString.count-1]
                mySong = mySong.replacingOccurrences(of: "%20", with: " ")
                mySong = mySong.replacingOccurrences(of: ".mp3", with: "")
                songs.append(mySong)
            }
        }
        myTableView.reloadData()
    }
    catch
    {
        print ("ERROR")
    }
}

没有从提供的代码中获得足够的条件 示例:在访问值之前,请务必检查array.count> 0。在您的情况下:

if songs.count > 0 { label.text = songs[thisSong] }

最新更新