swift:指数超出范围

时间:2017-11-23 07:22:11

标签: swift uitableview xcode9

我想从我添加到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")
    }
}

1 个答案:

答案 0 :(得分:0)

从提供的代码中获取的条件不足,但是如果要停止崩溃处理异常并处理代码的每个方案  示例:始终检查array.count>在访问值之前为0。 在你的情况下:

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