如何正确打印Swift中的块参数?
How to Correctly Print Block Parameter in Swift?
当我想在作为输入传递给函数的块中打印参数值时,我在 Swift 1.2 和 2.0 的 Playgrounds 中看到以下差异。任何有助于理解正在发生的事情的帮助将不胜感激!
func blockSample(myInput: String, myOutput: (answer: String) -> ()) {
myOutput(answer: myInput)
}
blockSample("testthis") { (answer) -> () in
print(answer) // This should print "testthis" but it doesn't
}
blockSample("testthis") { (answer) -> () in
print("test") // print something before the next line
print(answer) // this works. prints "testthis"
}
blockSample("testthis") { (answer) -> () in
let printedAnswer = answer
print(answer) // this works. prints "testthis". Note that I am printing answer and not printedAnswer
}
您的第一个示例确实没有打印 在 Playground 的实时面板中,这与其他示例相反。
但是 Xcode 7 Playgrounds 如果您打开菜单:
View / Debug Area / Show Debug Area
您将在控制台中看到所有内容均已正确打印。
在 Xcode 6 Playgrounds 中,您可以通过显示助理编辑器实现相同的目的:
View / Assistant Editor / Show Assistant Editor
此外,请记住,在 Playgrounds 中,您可以通过在单独的行中声明您的变量来强制在实时面板中显示一个值:
blockSample("testthis") { (answer) -> () in
answer // this will force the live display of the value for 'answer'
print(answer)
}
当我想在作为输入传递给函数的块中打印参数值时,我在 Swift 1.2 和 2.0 的 Playgrounds 中看到以下差异。任何有助于理解正在发生的事情的帮助将不胜感激!
func blockSample(myInput: String, myOutput: (answer: String) -> ()) {
myOutput(answer: myInput)
}
blockSample("testthis") { (answer) -> () in
print(answer) // This should print "testthis" but it doesn't
}
blockSample("testthis") { (answer) -> () in
print("test") // print something before the next line
print(answer) // this works. prints "testthis"
}
blockSample("testthis") { (answer) -> () in
let printedAnswer = answer
print(answer) // this works. prints "testthis". Note that I am printing answer and not printedAnswer
}
您的第一个示例确实没有打印 在 Playground 的实时面板中,这与其他示例相反。
但是 Xcode 7 Playgrounds 如果您打开菜单:
View / Debug Area / Show Debug Area
您将在控制台中看到所有内容均已正确打印。
在 Xcode 6 Playgrounds 中,您可以通过显示助理编辑器实现相同的目的:
View / Assistant Editor / Show Assistant Editor
此外,请记住,在 Playgrounds 中,您可以通过在单独的行中声明您的变量来强制在实时面板中显示一个值:
blockSample("testthis") { (answer) -> () in
answer // this will force the live display of the value for 'answer'
print(answer)
}