UITableViewController没有在swift中填充数据。 AnyObject不能转换为String

时间:2015-11-28 13:44:39

标签: ios swift uitableview

我对swift完全陌生,我很难发现它与obj.C完全不同 填充表格视图时遇到困难。

我的编码填充如下 -

    for day in range(1, months + 1):

当我编写以下代码class DetailTableViewController: UITableViewController { var items = [] override func viewDidLoad() { super.viewDidLoad() items=["dodnf","dgfd"] Item() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cellreuse", forIndexPath: indexPath) cell.textLabel?.text = items[indexPath.item] return cell } 时,我收到一条错误消息:cell.textLabel?.text = items[indexPath.item]

那么我的错误是什么?为什么会这样?

2 个答案:

答案 0 :(得分:2)

在声明数据源数组时添加类型:

var items : [String] = []

这就是全部。在cellForRowAtIndexPath中,编译器可以推断出类型。

然而,正确的语法应该是

cell.textLabel?.text = items[indexPath.row]

答案 1 :(得分:1)

问题是您已将items声明为数组而未指定元素的类型(var items = [])。因此,当您尝试从数组中获取元素时,编译器错误,因为它无法保证元素的类型是您所期望的。

您需要指定数组中项目的类型。您可以在两个可能的阶段中的任何一个阶段执行此操作:

  • 声明数组首选以利用Swift的类型安全性)时:

    var items = [String]() // or its equivalent: var items : [String] = []
    
    // Alternatively, if you know it at the time of declaration you can just do the following and let
    // Swift's type inference do its work
    var items = ["dodnf","dgfd"]
    
  • 或者从数组中获取元素

     cell.textLabel?.text = items[indexPath.item] as? String
    

您可以在The Swift Programming Language中了解有关Swift中集合类型的更多信息。