-6

I have this code, but it always shows me:

Type 'Any' has no subscript members

I don't know what happened. Thank you guys in advance, please explain me what I did wrong, because I don't know :(

 import UIKit
 class PicturesViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {       
     var posts = NSDictionary()   
     override func viewDidLoad() {
         super.viewDidLoad()
         posts = ["username" : "Hello"]
     }
     func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
         return posts.count
     }
     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
         let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PostCollectionViewCell
         cell.usernameLbl.text = posts[indexPath.row]!["username"] as? String
         cell.PictureImg.image = UIImage(named: "ava.jpg")
         return cell
     }
 }
faridorid
  • 33
  • 7

1 Answers1

0

You have a NSDictionary but are trying to use it as an array. What you need is an array of dictionaries.

I would recommend you changing your code a little bit.

var posts: [[String: String]] = [] // This creates an empty array of dictionaries.

override func viewDidLoad() {
    super.viewDidLoad()
    posts = [
        [ "username": "Hello" ] // This adds a dictionary as an element of an array.
    ]
}

...

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PostCollectionViewCell
    cell.usernameLbl.text = posts[indexPath.row]["username"] // This will work now.
    cell.PictureImg.image = UIImage(named: "ava.jpg")
    return cell
}
Senõr Ganso
  • 1,694
  • 16
  • 23