Swift 收到'的警告;让';模式没有效果;子模式为';不要绑定任何变量
我正在做以下事情,但我得到以下警告: “let”模式没有效果;子模式没有绑定任何变量Swift 收到'的警告;让';模式没有效果;子模式为';不要绑定任何变量,swift,enums,pattern-matching,Swift,Enums,Pattern Matching,我正在做以下事情,但我得到以下警告: “let”模式没有效果;子模式没有绑定任何变量 很简单。在这三种情况下,只有过道具有类型为Int的关联值。您的.middle&.window案例没有要提取的关联值,即没有要绑定的值。只要知道情况就是这样就足够了。要使警告消失,请更改: if case let .middle = seat 致: 同样适用于您的.window案例您可以使用开关 switch seat { case .middle: print("middle")
很简单。在这三种情况下,只有
过道
具有类型为Int
的关联值。您的.middle
&.window
案例没有要提取的关联值,即没有要绑定的值。只要知道情况就是这样就足够了。要使警告消失,请更改:
if case let .middle = seat
致:
同样适用于您的
.window
案例您可以使用开关
switch seat {
case .middle:
print("middle")
case .window:
print("window")
case let .aisle(row):
print("able to let row be the associatedvalue of seat; its value is: \(row)")
}
除其他2个正确答案外,如果您使座椅可平衡,则对于没有关联值的情况,您可以与
==
进行比较:
enum Seat: Equatable {
case middle
case window
case aisle(Int)
}
let m : Seat = .middle
let w : Seat = .window
let a : Seat = .aisle(5)
let seats = [m,w,a]
for seat in seats {
if seat == .middle {
print("middle")
}
else if seat == .window {
print("window")
}
else if case .aisle(let row) = seat {
print("able to let row be the associatedvalue of seat; its value is: \(row)")
}
}
注意:我还将最后一个case重写为
if case.roach(let row)=seat
,我认为当只有一个变量要绑定时,这会使let绑定更清晰。关于equalable
的有趣事情。我没想到。实际上我喜欢另一种方式。然后我可以这样理解它:如果我可以让row作为过道案例的关联值。我很难读懂你的。我可以这样理解:若过道case可以让row作为它的关联值,但这听起来很冗长。这有意义吗?关于意见的问题是两者都是有效的。绑定的变量是关联的值,因此我认为在行
旁边放置let
强调了这一点。如果与开关一起使用
所有3个案例都将以
开头,使其外观更加统一。最后一个案例也可以写成案例。过道(let row):
这使3个案例更加统一,并强调行
是绑定的变量。这两种方法都是有效的,只是偏好的问题。
switch seat {
case .middle:
print("middle")
case .window:
print("window")
case let .aisle(row):
print("able to let row be the associatedvalue of seat; its value is: \(row)")
}
enum Seat: Equatable {
case middle
case window
case aisle(Int)
}
let m : Seat = .middle
let w : Seat = .window
let a : Seat = .aisle(5)
let seats = [m,w,a]
for seat in seats {
if seat == .middle {
print("middle")
}
else if seat == .window {
print("window")
}
else if case .aisle(let row) = seat {
print("able to let row be the associatedvalue of seat; its value is: \(row)")
}
}