我正在尝试拆分一个类似于这样的字符串:
let Ingredients = "1:egg,4:cheese,2:flour,50:sugar"
我正在尝试获得这样的字典输出,内容如下:
var decipheredIngredients : [Int:String] = [
1 : "egg",
4 : "cheese",
2 : "flour",
50 : "sugar"
]
这是我正在尝试使用的代码
func decipherIngredients(input: String) -> [String:Int]{
let splitStringArray = input.split(separator: ",")
var decipheredIngredients : [String:Int] = [:]
for _ in splitStringArray {
decipheredIngredients.append(splitStringArray.split(separator: ":"))
}
return decipheredIngredients
}
当我尝试这样做时,出现了一个错误,说我不能向字典中添加内容。我已经尝试过其他类似的方法:
func decipherIngredients(input: String) -> [String.SubSequence]{
let splitStringArray = input.split(separator: ",")
return splitStringArray
}
let newThing = decipherIngredients(input: "1:egg,4:cheese,2:flour,50:sugar").split(separator: ":")
print(newThing)
但是我得到了这个函数的输出。
[ArraySlice(["1:egg", "4:cheese", "2:flour", "50:sugar"])]