鉴于以下内容,连接
的正确方法是什么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"
答案 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