Swift - 下标的模糊使用

时间:2017-08-11 20:58:00

标签: ios arrays swift

Total Swift noob在这里尝试学习如何构建小型应用程序,并且我已经在朋友和我在Medium上找到的一些源代码的帮助下得到了这一点。我能够在Simulator中编译和运行我的应用程序,但为我的iPhone编译会产生两个(类似的)错误。

第一个错误来自本节:

class BubblesEnglishCollectionViewController: UICollectionViewController {
let numberOfItemsPerRow = 3.0 as CGFloat
let interItemSpacing = 1.0 as CGFloat
let interRowSpacing = 1.0 as CGFloat
let sectionTitleKey = "SectionTitle"
let sectionItemsKey = "Items"
var data = [Dictionary<String,AnyObject>]()
override func viewDidLoad() {
    super.viewDidLoad()
    self.collectionView?.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 40, right: 0)
    if let path = Bundle.main.path(forResource: "BubblesEnglishData", ofType: ".plist") {
        let dict = NSDictionary(contentsOfFile: path) as! Dictionary<String,AnyObject>
        let allSections = dict["Sections"]
        if let selectedSections = UserDefaults.standard.array(forKey: "selectedSections") as? [Int] {
            for index in selectedSections {
            self.data.append((allSections![index]) as! Dictionary<String, AnyObject>)
            }
        }
    }
}

它表明我正在模糊地使用&#39;下标&#39;由于

self.data.append((allSections![index]) as! Dictionary<String, AnyObject>)

我在以下代码行中也收到了同样的错误:

override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    // Configure the cell
    guard let bubbleItem = cell as? BubbleCell else {
        return
    }
    let sectionItems = self.data[indexPath.section][sectionItemsKey]
    let imageName = sectionItems![indexPath.row] as! String
    bubbleItem.configure(usingImageName: imageName)
}

由于这一行:

let imageName = sectionItems![indexPath.row] as! String

对不起,如果我的问题没有意义,但这两个错误是阻止我编译的唯一因素。提前谢谢。

1 个答案:

答案 0 :(得分:0)

您正尝试使用[String: AnyObject]下标Int字典。将data设为[Int:AnyObject]或获取下标&#39; Stringdescription来修复该问题。

self.data.append((allSections![index.description]) as! Dictionary<String, AnyObject>)

let imageName = sectionItems![indexPath.row.description] as! String

另外请注意,除非您完全确定该值不是!,否则应避免使用隐式展开(nil)。请尝试使用guard letif let