2015-06-17 34 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

相關問題