Arrays 如何检查任意数组是否包含哪种数据类型的元素
我有一个类似于Arrays 如何检查任意数组是否包含哪种数据类型的元素,arrays,swift,Arrays,Swift,我有一个类似于[Any]的数组,我只是附加了一些字符串元素和UIImage元素。 最后,我将它列在UITableView中,在这里我需要显示一个图像,其中数组的索引为UIImage,元素的索引为string类型 class PhotosVC: UIViewController { var arrPhotos: [Any] = [Any]() override func viewDidLoad() { self.arrPhotos.append("stringV
[Any]
的数组,我只是附加了一些字符串
元素和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
}
}
只需使用is
可以直接进行类型检查。例如:
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)")
}
}
您可以通过以下多种方式完成:
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
}
只需要您是关键字,就可以检查数组中元素的类型
if array[index] is String {
print("isString Type")
}
else {
print("UIImage Type")
}
不要像这样在一个数组中组合不同的类型。你要么要处理安全施法的持续麻烦,要么要冒着强制施法的风险犯我的错误。请参阅,最好使用
开关
,以实际施法并有条件地将值绑定为特定类型
if array[index] is String {
print("isString Type")
}
else {
print("UIImage Type")
}