gpt4 book ai didi

swift:索引超出范围

转载 作者:行者123 更新时间:2023-11-30 11:59:23 24 4
gpt4 key购买 nike

我想播放我添加到 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com