简体   繁体   中英

Check the element is the number in the array

I have an array of elements consisting of digits and names of images.
I want to check that the i element of the array is the number or name of the image. Can someone suggest me the solution?
Thanks.

This is my array:

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]

This is my processing code before adding numbers to the array

 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
    }

This code block may help you

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

Result:

在此处输入图片说明

First thing you need to initialise your array as,

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]

Now you can update 'cellForItemAt' method like following,

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM