循环遍历[Any]数组

时间:2018-04-18 07:14:01

标签: ios arrays swift uicollectionview

我有一个定义为Any的数组由用户对象组成,每隔60个元素就会有一个“是”字符串。 该数组如下所示:

[user1,...user60,"Yes",user61,user62....,user119,"Yes"]

我希望将单元格1到单元格60显示为来自我的数组的用户,当数组中的项目为“是”时,显示另一个仅显示图像的单元格。然后集合视图将根据数组继续增长。

2 个答案:

答案 0 :(得分:1)

我认为user1 ... user119的类型为User,而不是你可以这样做:

let collection: [Any] = [user1,...user60,"Yes",user61,user62....,user119,"Yes"] 

for element in collection {
    if let user = element as? User {
        //do whatever you want with user class
    } else let yesString = element as? String, yesString == "Yes" {
        //you found "Yes" string
    } else {
       //unknown type
    }
}

当您想要使用collectionView数据源中的数据时,可以使用相同的逻辑,从数组中获取元素并执行相同操作以检查元素是User还是String值“是”。

由于问题中不清楚你是否需要“是”元素,你可以先从数组中删除“是”,然后你将得到一个数组[User]

由于您的collectionView将有两种类型的单元格:用户单元格和图像视图单元格,您必须首先注册它们以用于collectionView,如:

self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "userCellIdent")
self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "yesCellIdent")

(如果您有每种类型的自定义子类,大多数时候您应该为要注册的每种单元格类型替换UICollectionViewCell.self YourCollectionViewCellSubclassName.self

cellForItemAt你做:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let element = collection[indexPath.item]

    if let user = element as? User {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "userCellIdent", for: indexPath)
        //configure your cell with user data
        return cell
    } else if let yesString = element as? String, yesString == "Yes" {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "yesCellIdent", for: indexPath)
        //configure your with the image view when element in collection is "Yes"
        return cell
    } else {
        //you have something other than user and "Yes" in the collection
        fatalError()
    }
}

答案 1 :(得分:0)

您可以使用:

 let arrCollection: [Any] = [user1,...user60,"Yes",user61,user62....,user119,"Yes"]


    for data in arrCollection{

        if let strYes  == data as? String{
            print(strYes)
            print("yes found")

        }else{
            print("not Found")
        }
    }

希望它有所帮助。