【问题标题】:Why did I get: Type 'Any' has no subscript members [duplicate]为什么我得到:类型'Any'没有下标成员[重复]
【发布时间】:2017-11-25 21:45:16
【问题描述】:

我有这段代码,但它总是显示给我:

类型 'Any' 没有下标成员

我不知道发生了什么。 提前谢谢你们,请解释我做错了什么,因为我不知道:(

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

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您有一个 NSDictionary,但正试图将其用作数组。你需要的是一个字典数组。

    我建议您稍微更改一下代码。

    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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-06
      相关资源
      最近更新 更多