Swift 抛出表达式类型';字符串';不符合';错误';
迅捷的 此错误中的句柄抛出的表达式类型“String”不符合“error” //确认字符串到错误协议Swift 抛出表达式类型';字符串';不符合';错误';,swift,Swift,迅捷的 此错误中的句柄抛出的表达式类型“String”不符合“error” //确认字符串到错误协议 extension String: Error { } //create error enum BulletTrainError: Error{ case insufficientLightVoltage(neededLightVoltage: Int) } struct BulletTrain{
extension String: Error {
}
//create error
enum BulletTrainError: Error{
case insufficientLightVoltage(neededLightVoltage: Int)
}
struct BulletTrain{
func startPicnic(lightVoltage: Int) throws -> String {
if lightVoltage < 1000{
throw BulletTrainError.insufficientLightVoltage(neededLightVoltage: 1000 - lightVoltage)
}
if lightVoltage > 5000 {
throw "High Voltage"
}
return " lets go the picnic begin"
}
}
i think i am missing some thing here
objBulletTrain = BulletTrain()
let result = (try? objBulletTrain.startPicnic(lightVoltage: 2000)) ?? ""
print(result)
扩展字符串:错误{
}
//创建错误
枚举BulletTrainError:错误{
外壳照明电压不足(所需照明电压:Int)
}
结构子弹列车{
func startPicnic(lightVoltage:Int)抛出->字符串{
如果光电压<1000{
掷弹错误。照明电压不足(需要的照明电压:1000-照明电压)
}
如果光电压>5000{
抛出“高压”
}
return“让我们开始野餐”
}
}
我想我错过了一些东西
objBulletTrain=BulletTrain()
让结果=(try?objBulletTrain.startPicnic(lightVoltage:2000))??""
打印(结果)
将另一个案例添加到错误枚举中并抛出该案例错误非常明显。你不能乱扔绳子。遵循@matt的建议。