-
-
Save VincentSit/e0755219fce38c7df213073490d42a98 to your computer and use it in GitHub Desktop.
v2ex demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
func guard11(age:Int?) { | |
// 左边的 age 是本地变量, 与形参不是一个变量. | |
// 并不一定要和形参同名, 此处只是按惯例举例. | |
guard let age = age else { return } | |
// 本地变量 age 现在可以在此作用域内安全地访问, 不再需要解包. | |
guard age > 18 else { | |
print("guard: 你没有成年,不许进入, \(age)") | |
return | |
} | |
print("guard: 你是成年人,可以饮酒了, \(age)") | |
} | |
func guard12(age:Int?) { | |
// 或者这样写也可以. | |
guard let age = age, age > 18 else { | |
print("guard: 你没有成年,不许进入, \(age ?? 0)") | |
return | |
} | |
print("guard: 你是成年人,可以饮酒了, \(age)") | |
} | |
guard11(age: 17) | |
guard11(age: 19) | |
func if22(age:Int?){ | |
// Swift 中 if / for 等不需要括号 | |
// 左边的 age 只存在于 if 作用域中, 出了此作用域后无法被访问. | |
if let age = age, age > 18 { | |
print("if: 你没有成年,不许进入, \(age)") | |
return | |
} | |
// 这里的 age 是形参 age. 你无法访问到 if let 解包后的 age. | |
print("if: 你是成年人,可以饮酒了, \(age ?? 0)") | |
} | |
if22(age: 17) | |
if22(age: 19) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output:
guard: 你没有成年,不许进入, 17
guard: 你是成年人,可以饮酒了, 19
if: 你是成年人,可以饮酒了, 17
if: 你没有成年,不许进入, 19