我对Swift来说还很陌生,所以仍然会修补并找到解决方法。我只是想知道为什么我必须将Switch值chicken.breed, chicken.temper
和大写字母Breed.leghorn, Temper.hilarious
括在括号内。 删除括号后,看到以下错误
上下文
练习的目的是每当发现有趣的鸡与我想要检查的chickenOfInterestCount
和Breed
值匹配时就增加Temper
。所以我用了一个Switch语句来执行这些操作
Exercise.swift
var chickenOfInterestCount = 0
for chicken in chickens {
// check the chicken variables breed and temper enums
switch (chicken.breed, chicken.temper){
case (Breed.leghorn, Temper.hilarious):
chickenOfInterestCount += 1
default:
print("No match")
}
}
print(chickenOfInterestCount)
Chicken.swift
public enum Breed {
case leghorn, rhodeIsland, silkie, plymouthRock
}
public enum Temper {
case friendly, grumpy, hilarious
}
public struct Chicken {
public let breed: Breed
public let temper: Temper
}
public let chickens: [Chicken] = [
Chicken(breed: .leghorn, temper: .friendly),
Chicken(breed: .leghorn, temper: .friendly),
Chicken(breed: .leghorn, temper: .grumpy),
Chicken(breed: .rhodeIsland, temper: .friendly),
Chicken(breed: .leghorn, temper: .hilarious),
Chicken(breed: .rhodeIsland, temper: .friendly),
Chicken(breed: .rhodeIsland, temper: .grumpy),
Chicken(breed: .silkie, temper: .friendly),
Chicken(breed: .rhodeIsland, temper: .grumpy),
Chicken(breed: .silkie, temper: .grumpy),
Chicken(breed: .rhodeIsland, temper: .hilarious),
Chicken(breed: .leghorn, temper: .friendly),
Chicken(breed: .silkie, temper: .friendly),
Chicken(breed: .leghorn, temper: .hilarious),
Chicken(breed: .plymouthRock, temper: .grumpy),
Chicken(breed: .leghorn, temper: .grumpy),
Chicken(breed: .silkie, temper: .grumpy),
Chicken(breed: .plymouthRock, temper: .friendly),
Chicken(breed: .leghorn, temper: .friendly),
Chicken(breed: .leghorn, temper: .friendly),
]
删除亲本时出错
error: 19_EnumsAndSwitch.playground:9:25: error: expected '{' after 'switch' subject expression
switch chicken.breed, chicken.temper{
^
error: 19_EnumsAndSwitch.playground:10:9: error: 'case' label can only appear inside a 'switch' statement
case (Breed.leghorn, Temper.hilarious):
^
error: 19_EnumsAndSwitch.playground:12:9: error: 'default' label can only appear inside a 'switch' statement
default:
^
答案 0 :(得分:2)
switch
采用一个表达式。通过将两个值放在括号中,您将创建一个元组,并且case语句在该元组上匹配。
没有括号,您试图将两个逗号分隔的表达式放在只能有一个的地方。
在元组上使用switch
时,用例可以使元组的各种组合与switch
表达式中的组合匹配。
有关更多信息,请参见Swift书中的Tuples and Switch部分。