因此,想法是用户可以创建包含许多单词对的集合。
例如,他们创建了一个集合true
,并在其中添加了一些单词和单词的翻译。然后他们创建了另一个名为false
的集合,并添加了相应的键和值,等等:
nouns
如何在Swift中实现此功能?
这是否意味着每次用户添加新收藏集时我都必须创建新词典?
我尝试做类似的事情
colors
但是错误的数量不可数!正确的方法是什么?
更新:
userInput = {
nouns: {
"dog": "translation",
"cat": "translation",
"fish": "translation"
//etc
},
colors: {
"red": "translation",
"green": "translation",
"blue": "translation"
//etc
}
//etc..
}
答案 0 :(得分:2)
您需要
var main = [String: [String:String]]()
获取当前值
var collectionName = input.text! // nouns / colors
var inner:[String:String] = main[collectionName] ?? [:]
更改并重新设置
inner["dog"] = "translation"
main[collectionName] = inner
import UIKit
var main = [String: [String:String]]() // global
class ViewController: UIViewController {
@IBOutlet weak var collection: UITextField!
@IBOutlet weak var input1: UITextField!
@IBOutlet weak var input2: UITextField!
var collectionName = "nouns"
override func viewDidLoad() {
super.viewDidLoad()
var collectionName = collection.text! // collection.text! will be "" as textfield is empty when the above function is called
var inner:[String:String] = main[collectionName] ?? [:]
inner[input1.text!] = input2.text!
main[collectionName] = inner
}
@IBAction func click(_ sender: Any) {
print(main[collectionName])
}
}
OR
import UIKit
var main = [String: [String:String]]() // global
class ViewController: UIViewController {
@IBOutlet weak var collection: UITextField!
@IBOutlet weak var input1: UITextField!
@IBOutlet weak var input2: UITextField!
var collectionName = "nouns"
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func save(_ sender: Any) { // save button action
print("Before save : " , main)
var collectionName = collection.text!
var inner:[String:String] = main[collectionName] ?? [:]
inner[input1.text!] = input2.text!
main[collectionName] = inner
print("After save : " , main)
}
}