2017-08-11 128 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 ),關於如何重寫這個的任何提示?再次感謝你。 –