如何在Swift中正确打印块参数?

时间:2015-07-09 16:49:40

标签: swift swift-playground

我想在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
}

1 个答案:

答案 0 :(得分:1)

你的第一个例子确实没有在Playground的实时面板中打印 与其他人相反。

但是如果打开菜单,请使用Xcode 7 Playgrounds:

  

查看/调试区/显示调试区

您将在控制台中看到所有内容都已正确打印。

在Xcode 6 Playgrounds中,您可以通过显示助理编辑器来实现相同目的:

  

查看/助理编辑/显示助理编辑

另外,请记住,在Playgrounds中,只需在单独的行中声明变量,即可强制在实时面板中显示值:

class Counter(models.Model):

    SURVEY_WIZARD_TYPE_CHOICES = (
                              ('SURVEY_WIZARD_ONE', 'survey_wizard_one'),
                              ('SURVEY_WIZARD_TWO', 'survey_wizard_two'), 
                              ('SURVEY_WIZARD_THREE', 'survey_wizard_three'), 
                              ('SURVEY_WIZARD_FOUR', 'survey_wizard_four'), 
                              ('SURVEY_WIZARD_FIVE', 'survey_wizard_five'),
                              ('SURVEY_WIZARD_SIX', 'survey_wizard_six'), 
                              ('SURVEY_WIZARD_SEVEN', 'survey_wizard_seven'),
                              ('SURVEY_WIZARD_EIGHT', 'survey_wizard_eight'),
                              ('SURVEY_WIZARD_NINE', 'survey_wizard_nine'),
                              )   

    survey_wizard_type = models.CharField(max_length=1000, choices=SURVEY_WIZARD_TYPE_CHOICES)
    survey_wizard_count = models.SmallIntegerField(default=0)
    total_max_counter = models.SmallIntegerField(default=0)