ios Swift 中的 Switch 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25279000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Switch statement in Swift
提问by Evgeniy Kleban
I'm learning syntax of Swift and wonder, why the following code isn't working as I expect it to:
我正在学习 Swift 的语法,想知道为什么下面的代码没有像我期望的那样工作:
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)")
}
}
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?
我想在每次数字被 3(3、6、9、12 等)整除时打印 Fizz 并在每次它被 5 整除时打印 Buzz。缺少哪一块拼图?
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)")
}
}
I want to know how to solve this using Switch. Thank you.
我想知道如何使用 Switch 解决这个问题。谢谢你。
回答by Martin R
The usual rules for the FizzBuzz gameare to replace every multiple of 3 by "Fizz", every multiple of 5 by "Buzz", and every multiple of both 3 and5 by "FizzBuzz".
FizzBuzz 游戏的通常规则 是将 3 的每个倍数替换为“Fizz”,将 5 的每个倍数替换为“Buzz”,将 3和5 的每个倍数替换为“FizzBuzz”。
This can be done with a switch statement on the tuple (i % 3, i % 5)
.
Note that _
means "any value":
这可以通过元组上的 switch 语句来完成(i % 3, i % 5)
。请注意,这_
意味着“任何值”:
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)
}
}
回答by Thomas Zoechling
Switch statements in Swift support value bindings.
This allows you to assign a value that matches a certain condition (evaluated via the where
clause) to a temporary variable (x
& y
here):
Swift 中的 Switch 语句支持值绑定。
这允许您将匹配特定条件(通过where
子句评估)的值分配给临时变量(x
&y
此处):
for i in 1...100 {
switch (i){
case let x where x%3 == 0:
println("Fizz")
case let y where y%5 == 0:
println("Buzz")
default:
println("\(i)")
}
}
You could also use the assigned temp value in the case body.
您还可以在案例正文中使用分配的临时值。
Update:
Matt Gibson points out in the comments, that you can omit the assignment to a temp var if you are not going to use it in the case body.
So a more concise version of the above code would be:
更新:
Matt Gibson 在评论中指出,如果您不打算在案例正文中使用它,您可以省略对临时变量的分配。
因此,上述代码的更简洁版本将是:
for i in 1...100 {
switch (i){
case _ where i%3 == 0:
println("Fizz")
case _ where i%5 == 0:
println("Buzz")
default:
println("\(i)")
}
}
Side note: Your 2 code samples are slightly different (the first one uses the range 0-100 as input, while the second one operates on 1-100). My sample is based on your first code snippet.
旁注:您的 2 个代码示例略有不同(第一个使用范围 0-100 作为输入,而第二个在 1-100 上操作)。我的示例基于您的第一个代码片段。
回答by Suragch
This is a more general answer for people who come here just wanting to know how to use the switch
statement in Swift.
对于来到这里只是想知道如何switch
在 Swift 中使用该语句的人来说,这是一个更通用的答案。
General usage
一般用途
switch someValue {
case valueOne:
// executable code
case valueTwo:
// executable code
default:
// executable code
}
Example
例子
let someValue = "horse"
switch someValue {
case "horse":
print("eats grass")
case "wolf":
print("eats meat")
default:
print("no match")
}
Notes:
笔记:
- No
break
statement is necessary. It is the default behavior. Swiftswitch
cases do not "fall through". If you want them to fall through to the code in the next case, you must explicitly use thefallthrough
keyword. - Every case must include executable code. If you want to ignore a case, you can add a single
break
statement. - The cases must be exhaustive. That is, they must cover every possibly value. If it is not feasible to include enough
case
statements, adefault
statement can be included last to catch any other values.
- 无需
break
声明。这是默认行为。Swiftswitch
案例不会“失败”。如果您希望它们在下一个案例中出现在代码中,您必须明确使用fallthrough
关键字。 - 每个案例都必须包含可执行代码。如果要忽略大小写,可以添加单个
break
语句。 - 案例必须详尽无遗。也就是说,它们必须涵盖所有可能的值。如果包含足够多的
case
语句不可行,default
则可以最后包含一条语句以捕获任何其他值。
The Swift switch
statement is very flexible. The following sections include some other ways of using it.
Swiftswitch
语句非常灵活。以下部分包括使用它的一些其他方法。
Matching multiple values
匹配多个值
You can match multiple values in a single case if you use separate the values with commas. This is called a compound case.
如果使用逗号分隔值,则可以在单个情况下匹配多个值。这称为复合案例。
let someValue = "e"
switch someValue {
case "a", "b", "c":
// executable code
case "d", "e":
// executable code
default:
// executable code
}
You can also match whole intervals.
您还可以匹配整个间隔。
let someValue = 4
switch someValue {
case 0..<10:
// executable code
case 10...100:
// executable code
default:
// executable code
}
You can even use tuples. This example is adapted from the documentation.
你甚至可以使用元组。此示例改编自文档。
let aPoint = (1, 1)
switch aPoint {
case (0, 0):
// only catches an exact match for first and second
case (_, 0):
// any first, exact second
case (-2...2, -2...2):
// range for first and second
default:
// catches anything else
}
Value Bindings
值绑定
Sometimes you might want to create a temporary constant or variable from the switch
value. You can do this right after the case
statement. Anywhere that a value binding is used, it will match any value. This is similar to using _
in the tuple example above. The following two examples are modified from the documentation.
有时您可能希望从switch
值创建一个临时常量或变量。您可以在case
声明后立即执行此操作。在任何使用值绑定的地方,它将匹配任何值。这类似于_
在上面的元组示例中使用。以下两个示例是从文档中修改而来的。
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
// can use x here
case (0, let y):
// can use y here
case let (x, y):
// can use x or y here, matches anything so no "default" case is necessary
}
You can further refine the matching by using the where
keyword.
您可以使用where
关键字进一步细化匹配。
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
// executable code
case let (x, y) where x == -y:
// executable code
case let (x, y):
// executable code
}
Further study
进一步研究
- This answer was meant to be a quick reference. Please read the full documentationfor more. It isn't difficult to understand.
- 这个答案是为了快速参考。请阅读完整文档了解更多信息。不难理解。
回答by user6257714
This is how it can be done
这是如何做到的
var i = 0
switch i {
case i where i % 5 == 0 && i % 3 == 0: print(" Fizz Buzz")
case i where i % 3 == 0 : print("Fizz")
case i where i % 5 == 0 : print("Buzz")
default: print(i)
}
回答by Abhi Beckert
The industry standard behaviour of switch can lead to bugs similar to "Go to Fail".
交换机的行业标准行为可能会导致类似于“Go to Fail”的错误。
Basically the code doesn't always do exactly what it looks like the code will do when reading over it, which leads to code auditors skipping over critical bugs.
基本上,代码在阅读时并不总是完全按照代码看起来的方式执行,这会导致代码审计员跳过关键错误。
To counter that, Apple has decided switch statements should not work the same in Swift as the industry standard. In particular:
为了解决这个问题,Apple 决定 switch 语句在 Swift 中的工作方式不应与行业标准相同。特别是:
- There is an automatic break at the end of every case. It's impossible for more than one case statement to execute.
- If it's theoretically possible for one of the case statements to be missed, then the code will not compile at all. In swift one of the case statements will always execute, no matter what value is provided. If you provide an enum, every enum value must be handled. If a new value is added to an existing enum the code won't compile until new case statements are added. If you provide a 32 bit integer, you must handle every possible value of a 32 bit int.
- 每个案例结束时都有一个自动中断。执行多个 case 语句是不可能的。
- 如果理论上有可能遗漏 case 语句之一,那么代码将根本无法编译。在 swift 中,无论提供什么值,case 语句之一将始终执行。如果您提供枚举,则必须处理每个枚举值。如果向现有枚举添加新值,则在添加新 case 语句之前,代码不会编译。如果提供 32 位整数,则必须处理 32 位整数的每个可能值。
回答by BHASKAR
Use this code. Your logic is wrong. Your Switch Statement does not find the case accept 1 and 2
使用此代码。你的逻辑是错误的。你的 Switch 语句没有找到这种情况接受 1 和 2
class TEST1{
func print() -> Void{
var i = 0
for i in 1...100{
if Int(i%3) == 0 {
println("Fizz")
}
else if Int(i%5) == 0{
println("Buzz")
}
else {
println("\(i)")
}
}
}
}
var x = TEST1()
x.print()