swift:索引超出范围

标签 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
}

但是当我运行它时,这首歌没有出现在第一个 View Controller ,当我单击第二个 View Controller 选项卡时,应用程序崩溃,原因是:

index out of range

第一个 View Controller 代码如下:

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
}

以及我将歌曲传递到详细 View Controller 的方法:

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")
    }
}

第二个 View Controller 代码:

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。 对于你的情况:

ifongs.count > 0 { label.text = 歌曲[这首歌曲] }

关于swift:索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47449703/

相关文章:

ios - 从按钮的操作方法调用时 PrepareForSegue 不起作用 (Swift)

swift - xcdatamodeld 我必须填写所有属性吗

ios - Swift - UIViewControllerAnimatedTransitioning 未按预期使用 Swift4 进行转换

ios - Realm swift : Invalid value for property on xCode 9

swift - Xcode 中的 "' deinitialize() ' is deprecated: the default argument to deinitialize(count:) has been removed"警告

ios - 有没有办法从 Any 获取 Class(当 Any 是对象的实例时)?

Swift:WebKit View/WebView 禁用 JavaScript 或 Flash 等插件

ios - 如何在iOS swift中隐藏/查看标题 View 表

ios - 选择单元格时,UITableView 所有组件都更改了背景颜色

ios - 未调用 TableView 的 cellForRowAtIndexPath?