0

I am trying to populate my tableView with data from within an array, However when I try to assign the text of the Cell to the items in the array I keep getting the error:

Cannot assign value of type 'String.Type' to type 'String?

Here's my code as it stands, I've tried a few other ways but this one seems like it's the closest one.

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
  • Define structure like this struct Contacts {let name: String} Commented May 14, 2019 at 5:04
  • 1
    Unrelated but semantically you should name the struct Contact and the variable contacts. var contact:[Contacts]=[] and let contacts = contact[indexPath.row] is pretty confusing. Commented May 14, 2019 at 5:06

2 Answers 2

5

When you write "=" you're assigning a value, so when writing

let name = String.self

you're assigning the type of String to name. If you want to declare the type of a variable you should use semi-colon;

struct Contact {
  var name: String
}

If you quickly wants to populate your array with data just for testing, you can write:

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
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This fixed my issue! The problem was indeed in the way I was declaring my name string in the struct :)
0

You're not showing how you populate the array of Contacts, but the struct isn't declared correctly.

Presumably you want a struct that contains a name as a string. That would be declared such as:-

struct Contacts
{
  let name : String
}

Or with name declared with var instead of let if it needs to be variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.