小编Wal*_*sen的帖子

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

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

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)

split swift

2
推荐指数
1
解决办法
1113
查看次数

标签 统计

split ×1

swift ×1