gpt4 book ai didi

switch-statement - 为什么 Swift 允许非常量开关标签?

转载 作者:行者123 更新时间:2023-11-28 07:18:24 24 4
gpt4 key购买 nike

起初我对 Swift 感到鼓舞,因为你终于可以使用字符串编写 switch 语句,这意味着基于字典的代码现在几乎是可读的。

let kMyDictionaryKey1 = "one"  // use 'let' to declare constant dictionary key
let kMyDictionaryKey2 = "two" // use 'let' to declare constant dictionary key

println( "hello world" );

if ( true )
{
var dictionary = [kMyDictionaryKey1: 1, "two": 2, "three": 3]

for val in dictionary.keys {
switch val {
case kMyDictionaryKey1:
println( "yay switch on Key1" )
break

case kMyDictionaryKey2:
println( "yay switch on Key2" )
break

default :
println("world" )
break
} // end switch
}
}

上面的代码效果很好。

但是,我还注意到您可以将变量作为 case 标签。例如,您可以声明

var kMyDictionaryKey1 = "one"

在某些情况下我想这样做,但它似乎也很危险。它可能导致草率的代码和重复的开关标签。大多数语言不允许这样做,重复的标签是编译时错误。

是否有任何其他语言允许 case 标签的变量?

最佳答案

Switch 语句旨在成为您之前可能使用的一长串 if...else if...else if... 语句的更具表现力的形式,因此能够在 case 语句中使用变量、字符串和表达式。

您可以有多个具有相同 case 的 case 语句,但第一个匹配的 case 总是被执行。

此外,在 Swift 中,switch 语句没有 fall-through,因此不需要使用 break 语句。

var testVal = "one"

var result = 0

switch(testVal)
{
case "one":
result = 1
case "one":
result = 2
default:
result = 3
}

result // the result is 1

关于switch-statement - 为什么 Swift 允许非常量开关标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24025928/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com