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 语句


基础教程推荐
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01