Swift if-else语句介绍和用法示例

Swift的if-else语句包含两个语句:if语句和else语句。

如果测试评估为true, 则执行if语句;如果测试评估为false, 则执行else语句。

句法:

if expression {
	// statements
} else {
	// statements
}

例:

let number = 5
if number > 0 {
	print("This is a positive number.")
} else {
	print("This is not a positive number.")
}
print("This will be executed anyways.")

输出

This is a positive number.
This will be executed anyways.

在上面的程序中, 常数为正(5), 因此, 测试用例的评估结果为true, 并执行if代码块内的语句。

让我们将常数值更改为负数(-5), 并且测试条件相同。

let number = -5
if number > 0 {
	print("This is a positive number.")
} else {
	print("This is not a positive number.")
}
print("This will be executed anyways.")

输出

This is not a positive number.
This will be executed anyways.

你可以看到它在else的代码块内执行了该语句。


微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_47370.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?