Search code examples
iosswiftdictionarytextview

Cannot assign a value of type '[(String)]' to a value of type 'String!'?


woodText.text = [String](textForWood.values) This is my code. woodText is a UITextView, and textForWood is a dictionary. Please help.


Solution

  • woodText.text = textForWood["Oak"] as! String
    

    You need to assign a String to the text of a UITextView. The above shows how to extract a String from a Dictionary.

    Addition based on the comments

    I don't think using a dictionary to populate a table view is a good idea. (Remember, dictionaries are not ordered, arrays are.) You should have an array of some kind that informs the table view how many rows it should display and what to display in those rows.

    One solution would be an array of dictionaries ([[String : String]]). You can then populate each cell in cellForRowAtIndexPath. The dictionary for each row should contain something like

    ["name" : "Oak", "text" : "The text to display in the oak cell..."]
    

    Use the standard boilerplate code to dequeue the cell with the text view and then

    let woodDictionary = textForWood[indexPath.row]!
    woodText.text = woodDictionary["text"] as! String
    

    It would be much better to use a simple object.

    struct Wood {
        let name: String
        let text: String
    }