无法将类型“ String.Type”的值分配为类型“ String?” -迅捷

时间:2019-05-14 04:53:09

标签: swift

我正在尝试用数组中的数据填充tableView,但是当我尝试将Cell的文本分配给数组中的项目时,却不断出现错误:

  

无法将类型为'String.Type'的值分配为类型为'String?

这是我目前的代码,我尝试了其他几种方法,但这似乎是最接近的一种。

class ContactViewController: UIViewController, UITableViewDataSource {

  var contact:[Contacts]=[]

  struct Contacts {
     let name = String.self;
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath)
        let contacts = contact[indexPath.row]
        cell.textLabel?.text = contacts.name //This is where I get the error
        return cell
   }
}

2 个答案:

答案 0 :(得分:2)

当您输入“ =”时,您将分配一个值,因此在编写时

let name = String.self

您正在将String类型分配给name。如果要声明变量的类型,则应使用分号;

struct Contact {
  var name: String
}

如果您很快想用仅用于测试的数据填充数组,则可以编写:

struct Contact {
    var name: String
}

class ContactViewController: UIViewController, UITableViewDataSource {

  var contacts = [
      Contact(name: "First Contact"),
      Contact(name: "Second Contact"),
      Contact(name: "Third Contact")
  ]

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath)
        let contact = contacts[indexPath.row]
        cell.textLabel?.text = contact.name //This is where I get the error
        return cell
   }
}

答案 1 :(得分:0)

您没有显示如何填充Contacts的数组,但是未正确声明该结构。

大概您想要一个包含名称作为字符串的结构。可以这样声明:-

struct Contacts
{
  let name : String
}

或者如果需要变量,则使用name而不是var声明的let

相关问题