gpt4 book ai didi

arrays - 从数组中获取特定值以在 NSIndexpath.row 中返回

转载 作者:可可西里 更新时间:2023-11-01 01:29:05 24 4
gpt4 key购买 nike

我希望我的 Collection View 只返回特定的数组。我希望它仅从“AUDI”返回到“Chevrolet”或 [2...9]。汽车制造商和新汽车制造商数组的值均为 8。它们应该相同,但它给我错误 fatal error: Index out of bounds。我做错了什么??

 var car make = ["Honda","Toyota","AUDI","Bentley","BMW","Mercedes","Buick","Cadillac","KIA","Chevrolet","Corvette","Dodge","FIAT","Ford","GMC","Hyundai","Infiniti","Jaguar","JEEP","LandRover","LEXUS","Mazda","Nissan","RAM","Porsche","Scion","Volkswagen"]

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

return carmake[2...9].count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = viewcontrol.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! jobtypeCollectionViewCell

let newcarmake = carmake[2...9]
cell.title.text = newcarmake[indexPath.row]
return cell
}

最佳答案

carmake[2...9] 不是一个数组而是一个ArraySlice,和数组切片使用与创建它们的数组相同的索引。所以 carmake[2...9] 的有效索引是 2...9,而不是 0...7如您所料。

一个解决方案是创建一个真正的数组:

let newcarmake = Array(carmake[2...9])
cell.title.text = newcarmake[indexPath.row]

或者,用一个简单的引用原始数组偏移量计算,例如

cell.title.text = carmake[indexPath.row + 2]

关于arrays - 从数组中获取特定值以在 NSIndexpath.row 中返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39882800/

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