2017-08-11 74 views
-1

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

第一个错误出现本条:

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

它说我在做暧昧使用“标”由于

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 

对不起,如果我的问题没有意义,但这两个错误是唯一阻止我编译的东西。先谢谢你。

回答

0

您正在试图为下标字典Int。将data设为[Int:AnyObject],或者使用description获取下标'String的值来解决该问题。

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

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

在另一方面,你应该避免使用隐式的解包(!),除非你有绝对的把握,该值将不会nil。请尝试使用guard letif let

+1

或者使数据字典成为Dictionary 而不是String。 –

+0

@AndyRich真的,编辑我的答案。 – the4kman

+0

非常感谢你们。这允许它编译。然而,我的资产没有一个显示出来,正如你所预测的那样,@ 4kman,隐含的解包是有错误的。这行代码导致它: self.data.append((allSections![index.description])as!Dictionary ),关于如何重写这个的任何提示?再次感谢你。 –