如何将字符串拆分为Int:String Dictionary

Wal*_*sen 2 split swift

所以我试图拆分一个看起来像这样的字符串:

let Ingredients = "1:egg,4:cheese,2:flour,50:sugar"
Run Code Online (Sandbox Code Playgroud)

我试图得到这样的字典输出

var decipheredIngredients : [Int:String] = [

1 : "egg",
4 : "cheese",
2 : "flour",
50 : "sugar"

]
Run Code Online (Sandbox Code Playgroud)

这是我尝试使用的代码

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
}
Run Code Online (Sandbox Code Playgroud)

当我尝试这个时,我得到一个错误,说我无法附加到字典中.我尝试过这样的其他方法:

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)
Run Code Online (Sandbox Code Playgroud)

但我得到这个作为函数的输出

[ArraySlice(["1:egg", "4:cheese", "2:flour", "50:sugar"])]
Run Code Online (Sandbox Code Playgroud)

Den*_*ink 7

使用Swift 4和函数式编程的另一种方法:

let ingredients = "1:egg,4:cheese,2:flour,50:sugar"

let decipheredIngredients = ingredients.split(separator: ",").reduce(into: [Int: String]()) {
  let ingredient = $1.split(separator: ":")

  if let first = ingredient.first, let key = Int(first), let value = ingredient.last {
    $0[key] = String(value)
  }
}

print(decipheredIngredients)
Run Code Online (Sandbox Code Playgroud)