我正在尝试将枚举传递给对该枚举的参数进行运算的函数。我收到此错误:
Expression type 'Bool' is ambiguous without more context
相同的错误在等效的if子句中发生,因此,导致问题的原因不是三元运算符本身。
enum auto {
case pkw (SerialNumber: String, Axles: Int, Weight: Float)
case lkw (SerialNumber: String, Axles: Int, Weight: Float)
}
func checkIntegrity(car: auto) -> Bool {
switch car {
case .pkw:
if (checkSerialNumber(serialNumber: .pkw.SerialNumber.rawValue)
&& checkWeight(weight: .pkw.Weight.rawValue)) { // Error here, "&&" is underlined
return true
} else {
return false
}
break;
case .lkw:
return (checkSerialNumber(serialNumber: .lkw.SerialNumber.rawValue)
&& checkWeight(weight: .lkw.Weight.rawValue)) ? true : false; // same error here, "&&" is underlined
break;
default:
return false
}
被调用的其他函数仅返回一个布尔值:
func checkSerialNumber(serialNumber: String) -> Bool {
return serialNumber.contains("ABABWA") // changed after a hint in the comments
}
func checkWeight(weight: Float) -> Bool {
return (weight < 2)
}
我怀疑枚举及其使用方式存在问题,但是我还没有找到解决方案。
答案 0 :(得分:3)
该错误消息具有误导性。您要检查关联的值 枚举值,因此您必须将它们绑定在案例模式中:
func checkIntegrity(car: auto) -> Bool {
switch car {
case let .pkw(serialNumber, _, weight):
if checkSerialNumber(serialNumber: serialNumber)
&& checkWeight(weight: weight) {
return true
} else {
return false
}
break;
case let .lkw(serialNumber, _, weight):
return (checkSerialNumber(serialNumber: serialNumber)
&& checkWeight(weight: weight)) ? true : false;
break;
default:
return false
}
}
这可以简化为
func checkIntegrity(car: auto) -> Bool {
switch car {
case let .pkw(serialNumber, _, weight),
let .lkw(serialNumber, _, weight):
return checkSerialNumber(serialNumber: serialNumber) && checkWeight(weight: weight)
}
}
答案 1 :(得分:0)
尝试一下:
enum auto {
case pkw (SerialNumber: String, Axles: Int, Weight: Float)
case lkw (SerialNumber: String, Axles: Int, Weight: Float)
}
func checkSerialNumber(serialNumber: String) -> Bool {
return serialNumber.contains("ABABWA") ? false : true
}
func checkWeight(weight: Float) -> Bool {
return (weight < 2) ? true : false
}
func checkIntegrity(car: auto) -> Bool {
switch car {
case .pkw(let serialNumber, _, let weight):
return (checkSerialNumber(serialNumber: serialNumber) && checkWeight(weight: weight))
case .lkw(let serialNumber, _, let weight):
return (checkSerialNumber(serialNumber: serialNumber) && checkWeight(weight: weight))
}
}