如何在字典中添加值?

How do I add values in dictionary?

我正在制作一个 iOS 笔记应用程序,它需要标题和笔记。我的标题有 textField,笔记有 textView。然后我将这两个添加到一个数组中,并将它们附加到我的 tableView 中,我们可以在其中看到标题和注释。我正在使用的代码将我的所有注释附加到 tableView 中,并为所有标题显示相同的内容。我知道我必须为此使用 dictionary 但我该如何实现呢?这是 VC 的代码,其中包含 textViewtextField

@IBAction func addItem(_ sender: Any)
{
        list.append(textField.text!)
        list2.append(notesField.text!)
}

其中 listlist2 为空 array 在我的 tableView 中,我有可扩展的单元格,其中有一个 textView 来显示 list2 的内容,VC 的代码是:

override func awakeFromNib() {
    super.awakeFromNib()

    textView.text = list2.joined(separator: "\n")

}

您通过赋值将元素添加到 Swift 中的字典:

var dict = [String : String]()

let title = "My first note"
let body = "This is the body of the note"

dict[title] = body // Assigning the body to the value of the key in the dictionary

// Adding to the dictionary
if dict[title] != nil {
    print("Ooops, this is not to good, since it would override the current value") 

    /* You might want to prefix the key with the date of the creation, to make 
    the key unique */

} else {
// Assign the value of the key to the body of the note
    dict[title] = body
}

然后您可以使用元组遍历字典:

for (title, body) in dict {
    print("\(title): \(body)")
}

如果您只对 body 或标题感兴趣,您可以通过将标题或 body 替换为 _ 来忽略其他内容,如下所示:

for (_, body) in dict {
    print("The body is: \(body)")
}
// and
for (title, _) in dict {
    print("The title is: \(title)")
}

title/body 也可以通过字典的键或值属性访问:

for title in dict.keys {
    print("The title is: \(title)")
}
// and
for body in dict.values {
    print("The body is: \(body)")
}

只需要一个字典数组

var arrOfDict = [[String :AnyObject]]()
var dictToSaveNotest = [String :AnyObject]()

@IBAction func addItem(_ sender: Any)
{
  dictToSaveNotest .updateValue(textField.text! as AnyObject, forKey: "title")
  dictToSaveNotest .updateValue(NotesField.text! as AnyObject, forKey: "notesField")
  arrOfDict.append(dictToSaveNotest)
}

并且只需在 tableView 数据源方法中填充它只需在 tableViewCell 中制作两个出口 Class titleLable 和 notesLabel

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
 var cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! yourTableViewCell

        cell.titleLabel.text = arrayOfDict[indexPath.row]["title"] as! String!
        cell.notesLabel.text = arrayOfDict[indexPath.row]["notesField"] as! String!

        return cell
    }

注意:我没有在代码上测试它,但希望它一定能工作。 祝一切顺利 。