检查元素是否为数组中的数字

时间:2018-07-09 06:43:53

标签: ios arrays swift

我有一个由数字和图像名称组成的元素数组。
我想检查数组的i元素是图像的编号还是名称。 有人可以建议我解决方案吗?
谢谢。

这是我的数组:

var images = ["icon_theme_sports_badminton",9,1,"icon_theme_sports_baseball",7,"icon_theme_sports_basketball",3,"icon_theme_sports_bicycle",6,"icon_theme_sports_bowling",2,"icon_theme_sports_football",4,"icon_theme_sports_golf","icon_theme_sports_pingpong",8,5,"icon_theme_sports_s_ski","icon_theme_sports_s_swimming",0]

这是在将数字添加到数组之前的处理代码

 func collectionView (collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier ("collection_cell", forIndexPath: indexPath) as! SelectCollectionViewCell
        cell.image_icon.image = UIImage (named: images [indexPath.row])
        return cell
    }

2 个答案:

答案 0 :(得分:0)

此代码块可能对您有帮助

var images: [Any] = ["icon_theme_sports_badminton",9,1,"icon_theme_sports_baseball",7,"icon_theme_sports_basketball",3,"icon_theme_sports_bicycle",6,"icon_theme_sports_bowling",2,"icon_theme_sports_football",4,"icon_theme_sports_golf","icon_theme_sports_pingpong",8,5,"icon_theme_sports_s_ski","icon_theme_sports_s_swimming",0]


for arrayElement in images {

    if let numberElement = arrayElement as? Int {
        print("Array element is number: \(numberElement)")
    } else if let stringElement = arrayElement as? String {
        print("Array element is string: \(stringElement)")
    } else {
        print("Array element is not a number or string: \(arrayElement)")
    }
}

结果:

enter image description here

答案 1 :(得分:0)

首先需要将数组初始化为

var images = ["icon_theme_sports_badminton",9,1,"icon_theme_sports_baseball",7,"icon_theme_sports_basketball",3,"icon_theme_sports_bicycle",6,"icon_theme_sports_bowling",2,"icon_theme_sports_football",4,"icon_theme_sports_golf","icon_theme_sports_pingpong",8,5,"icon_theme_sports_s_ski","icon_theme_sports_s_swimming",0] as [Any]

现在您可以像下面这样更新'cellForItemAt'方法

func collectionView (collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier ("collection_cell", forIndexPath: indexPath) as! SelectCollectionViewCell
if images[indexPath.row] is Int {
    cell.image_icon.image = UIImage (named: "Default.png")
 } else {
    cell.image_icon.image = UIImage (named: images [indexPath.row])
 }   
return cell

}

相关问题