我有一个enum案例数组,我想对这些案例运行一个switch语句,但是收到这个错误:'[Enum case''North'在类型[Directions]中找不到。
enum Directions {
case north
case west
case east
case south
static let all = [north, west, east, south]
}
class MyViewController {
var directions = Directions.all
func foo () {
switch directions {
case .north: // Error here ('Enum case 'North' not found in type '[Directions]')
print("Going north")
}
}
}
答案 0 :(得分:2)
首先需要遍历阵列,然后才能使用开关
func foo () {
for direction in directions {
switch direction {
case .north: print("Going north")
case .west: print("Going west")
case .east: print("Going east")
case .south: print("Going south")
}
}
}
枚举的名称应为单数,因此
Direction
代替Directions
答案 1 :(得分:0)
the problem is that you are comparing a array of Directions type to an Directions enum case. You need to compare a particular element of array as listed below:
enum Directions {
case north
case south
case east
case west
static let all = [north, west, east, south]
}
class MyViewController {
var dir = Directions.all
func testing(){
switch dir[0] {
case .north:
print("north")
default:
print("default")
}
}
}
var a = MyViewController()
a.testing()
// out put : north
答案 2 :(得分:-3)
您可以使用以下方式提及代码
enum Directions {
case north
case west
case east
case south
}
class MyViewController {
func foo () {
switch Directions
{
case Directions.north:
print("Going north")
}
}
}