Switch statement in Swift(Swift 中的 switch 语句)
问题描述
我正在学习 Swift 的语法,我想知道为什么下面的代码没有像我预期的那样工作:
I'm learning syntax of Swift and wonder, why the following code isn't working as I expect it to:
for i in 1...100{
switch (i){
case 1:
Int(i%3) == 0
println("Fizz")
case 2:
Int(i%5) == 0
println("Buzz")
default:
println("(i)")
}
}
我想在每次数字可以被 3 整除(3、6、9、12 等)时打印 Fizz,并在每次可以被 5 整除时打印 Buzz.缺少哪一块拼图?
I want to print Fizz every time number is divisible by 3 (3, 6, 9, 12, etc) and print Buzz every time it's divisible by 5. What piece of the puzzle is missing?
注意:我确实使用以下方法解决了它:
Note: I did solve it using the following:
for ( var i = 0; i < 101; i++){
if (Int(i%3) == 0){
println("Fizz")
} else if (Int(i%5) == 0){
println("Buzz")
} else {
println("(i)")
}
}
我想知道如何使用 Switch 来解决这个问题.谢谢.
I want to know how to solve this using Switch. Thank you.
推荐答案
FizzBuzz 游戏的常用规则一>将每个 3 的倍数替换为Fizz",将每个 5 的倍数替换为Buzz",以及FizzBuzz"的和 5 的每3 个倍数.
The usual rules for the FizzBuzz game are to replace every multiple of 3 by "Fizz", every multiple of 5 by "Buzz", and every multiple of both 3 and 5 by "FizzBuzz".
这可以通过元组 (i % 3, i % 5) 上的 switch 语句来完成.请注意,_ 表示任何值":
This can be done with a switch statement on the tuple (i % 3, i % 5).
Note that _ means "any value":
for i in 1 ... 100 {
switch (i % 3, i % 5) {
case (0, 0):
print("FizzBuzz")
case (0, _):
print("Fizz")
case (_, 0):
print("Buzz")
default:
print(i)
}
}
这篇关于Swift 中的 switch 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Swift 中的 switch 语句
基础教程推荐
- Android Volley - 如何动画图像加载? 2022-01-01
- UIImage 在开始时不适合 UIScrollView 2022-01-01
- Play 商店的设备兼容性问题 2022-01-01
- 如何将图像从一项活动发送到另一项活动? 2022-01-01
- SwiftUI-ScrollViewReader的ScrollTo不滚动 2022-01-01
- 为什么姜饼模拟器方向卡在应用程序中? 2022-01-01
- iOS - UINavigationController 添加多个正确的项目? 2022-01-01
- navigationItem.backBarButtonItem 不工作?为什么上一个菜单仍然显示为按钮? 2022-01-01
- 如何比较两个 NSDate:哪个是最近的? 2022-01-01
- Xcode UIView.init(frame:) 只能在主线程中使用 2022-01-01
