如何将字典中的值与字符串连接起来

时间:2014-08-10 22:32:16

标签: swift

鉴于以下内容,连接

的正确方法是什么
var sets = [[ "reps": 10, "weight": 100 ], [ "reps": 10, "weight": 100 ], [ "reps": 10, "weight": 100 ]]
var text = sets[0]["reps"] + " reps"

唯一有用的是下面的代码,但我不明白为什么。理想情况下,我可以简单地使用字符串插值,但这似乎会产生语法错误。

var text = sets[0]["reps"]!.description + " reps"

2 个答案:

答案 0 :(得分:2)

更新了Swift 2

sets的类型为[[String : Int]]。因此,为了从String获得Int,您必须使用string interpolation或使用String初始值设定项。

根据您的需要,您可以选择以下Playground示例之一:

可选绑定+ String初始值设定项:

let sets = [[ "reps": 10, "weight": 100 ], [ "reps": 10, "weight": 100 ], [ "reps": 10, "weight": 100 ]]
if let int = sets[0]["reps"] {
    let text =  String(int) + " reps"
    print(text) // prints: "10 reps"
}

可选绑定+字符串插值:

let sets = [[ "reps": 10, "weight": 100 ], [ "reps": 10, "weight": 100 ], [ "reps": 10, "weight": 100 ]]
if let int = sets[0]["reps"] {
    let text =  "\(int)" + " reps"
    print(text) // prints: "10 reps"
}

可选强制解包:

let sets = [[ "reps": 10, "weight": 100 ], [ "reps": 10, "weight": 100 ], [ "reps": 10, "weight": 100 ]]
let int = sets[0]["reps"]! // Use forced unwrapping with caution
let text =  "\(int)" + " reps"
print(text) // prints: "10 reps"

答案 1 :(得分:1)

sets[0]["reps"]是一个int。您可以使用格式指定类型:

var weight = sets[0]["reps"]!
var text = String(format: "%d reps", weight)

或一体化:

var text = String(format: "%d reps", sets[0]["reps"]!)

println("text: \(text)") // text: 10 reps