Как проверить, есть ли массив ЛЮБОГО, какой тип данных элемента - PullRequest
0 голосов
/ 07 мая 2018

У меня есть массив вроде [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 голосов
/ 08 мая 2018

Просто нужно вам IS ключевое слово, чтобы проверить тип элемента в массиве

if array[index] is String {
    print("isString Type")
}
else {
    print("UIImage Type")
}
0 голосов
/ 07 мая 2018

Возможно сделать проверку типа напрямую. Например:

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)")
    }
}
0 голосов
/ 07 мая 2018

Вы можете сделать это разными способами, например:

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
   }
0 голосов
/ 07 мая 2018

Просто используйте - это

  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
    }
...