2015-06-17 25 views
3

为什么守卫让x = x在一个方法内的行为与外部不同?为什么警卫让x = x表现出不同的范围行为?

下面的示例代码被从Playground复制出来。

var x:Int? = 3 

func foo(x: Int?) { 
    guard let x = x else { 
     return 
    } 

    print(x) // print "3\n" 
} 

foo(x) 

guard let x = x else { 
    throw NSError(domain: "app", code: 0, userInfo: nil) 
} 

print(x) // print "Optional(x)\n" 

回答

8

guard语句需要一个returnbreakcontinuethrow他们else条款。如果更正x?.description中的可选项,编译器将指出该错误。在函数范围之外使用守护进程是没有意义的,因为它意味着检查一个条件,如果它无效,则跳出该范围。您将得到错误:

guard body may not fall through.

它是在一个操场有效的唯一方法(或功能范围之外的)是抛出一个错误。

按照documentation

The else clause of a guard statement is required, and must either call a function marked with the noreturn attribute or transfer program control outside the guard statement’s enclosing scope using one of the following statements:

  • return
  • break
  • continue
  • throw
+0

我仍然看到其投射不同的范围的行为。请参阅编辑的文章 – Boon

+0

Swift民间证实了这一点 - 显然这是一个编译器错误。 – Boon

相关问题