2017-01-03 60 views
-2

當我做出遷移SWIFT代碼我有這個錯誤「類型‘任何’有沒有下成員」和我的代碼是遷移迅速向SWIFT 3的NSMutableArray

var myArray: NSMutableArray = [] 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ 
    let cell = UITableViewCell() 
    if let name = self.myArray[(indexPath as NSIndexPath).row]["FirstName"] as? String{ 
     cell.textLabel?.text = ("\(name)") 
     } 
} 

我嘗試了很多事情,但我沒有這個問題的答案。

+0

看來你需要告訴編譯器'self.myArray [(indexPath爲NSIndexPath).row]'是一本字典(和被允許使用'[「姓」 ]',訪問它的關鍵'FirstName'的值)? – Larme

+4

不要使用'NSMutableArray'。使用Swift數組。 – rmaddy

+0

嘗試var myArray:Array ? –

回答

3

第一的ll:請勿在Swift中使用NSMutableArray

發生此錯誤的原因是編譯器需要知道對象是否可以通過密鑰進行腳註。使用本地Swift類型解決了這個問題。

var myArray = [[String:Any]]() 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ 
    let cell = UITableViewCell() // will not work 
    if let name = self.myArray[indexPath.row]["FirstName"] as? String { // optional binding actually not needed 
     cell.textLabel?.text = name // please no string interpolation 
    } 
    return cell // mandatory! 
} 

注意:考慮UITableViewCell()將無法​​正常工作。推薦的方法是可重複使用的細胞

let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) 
+0

謝謝。這是結果:) – HideCode

0

您應該使用

  • 泛型
  • dequeueReusableCell
  • IndexPath,而不是NSIndexPath

所以這裏的代碼

import UIKit 

class Controller: UITableViewController { 

    var persons = [[String:String]]() 

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ 
     let cell = tableView.dequeueReusableCell(withIdentifier: "MyCellID") ?? UITableViewCell(style: .default, reuseIdentifier: "MyCellID") 
     cell.textLabel?.text = persons[indexPath.row]["FirstName"] 
     return cell 
    } 
} 
+1

此方法的'override'僅適用於'UITableViewController'。如果它是另一種實現該協議的類,這裏沒有覆蓋。此外,從Swift 1/2遷移到Swift 3也是無關緊要的。 –

+0

@Cœur:好點 –