如何检查ANY数组包含哪些数据类型的元素

时间:2018-05-07 19:29:14

标签: arrays swift

我有一个像[Any]这样的数组,我只是添加了一些String元素和UIImage元素。 最后,我将它列入UITableView,我需要在其中显示一个图像,其中数组的索引具有UIImage和字符串,其中元素的索引具有String类型。

class PhotosVC: UIViewController {

    var arrPhotos: [Any] = [Any]()

    override func viewDidLoad() {
        self.arrPhotos.append("stringValue")
        self.arrPhotos.append(pickedImage)
        self.collectionViewData.reloadData()
    }
}
extension PhotosVC: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return arrPhotos.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotosDescCell", for: indexPath) as! PhotosDescCell

        if arrPhotos[indexPath] == String { // how to check here is element is String type or UIImage
            cell.lblDesc.text = arrPhotos[indexPath] as? String
        }
        else {
            cell.imgPhotos.image = arrPhotos[indexPath.row] as? UIImage
        }
        return cell
    }
}

4 个答案:

答案 0 :(得分:1)

只需使用

即可
  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotosDescCell", for: indexPath) as! PhotosDescCell

        if arrPhotos[indexPath] is String { 
            cell.lblDesc.text = arrPhotos[indexPath] as? String
        }
        else {
            cell.imgPhotos.image = arrPhotos[indexPath.row] as? UIImage
        }
        return cell
    }

答案 1 :(得分:1)

可以直接进行类型检查。例如:

var arrPhotos = [Any]()
arrPhotos.append("Some string")
if let five = Int("5") {
    arrPhotos.append(five)
}

for value in arrPhotos {
    if value is String {
        print("String \(value)")
    } else if value is Int {
        print("Int \(value)")
    } else {
        print("Not interesting \(value)")
    }
}

答案 2 :(得分:0)

您可以通过以下方式实现:

if arrPhotos[indexPath] is String { 
   cell.lblDesc.text = arrPhotos[indexPath.row] as? String
 }

:它还会打开值

if let textData = arrPhotos[indexPath.row] as? String {
       cell.lblDesc.text = textData
   }

答案 3 :(得分:0)

只需要 IS 关键字来检查数组中元素的类型

if array[index] is String {
    print("isString Type")
}
else {
    print("UIImage Type")
}