如何从if-else或switch case返回多个值

  • 本文关键字:返回 case switch if-else swift
  • 更新时间 :
  • 英文 :


我仍然是新手,学习Swift,所以我只是想知道是否有一些方法可以用更短的方式编写这段代码,而不重复三次?

var meterCalc: Double {
let lengthInput = Double(lengthIn1) + Double(lengthIn2)/100

if lengthUnit == 0 {
return lengthInput
} else if lengthUnit == 1 {
return lengthInput / 39.37
} else {
return lengthInput / 3.281
}
}
var inchCalc: Double {
let lengthInput = Double(lengthIn1) + Double(lengthIn2)/100

if lengthUnit == 0 {
return lengthInput * 39.37
} else if lengthUnit == 1 {
return lengthInput
} else {
return lengthInput * 12
}
}
var feetCalc: Double {
let lengthInput = Double(lengthIn1) + Double(lengthIn2)/100

if lengthUnit == 0 {
return lengthInput * 3.281
} else if lengthUnit == 1 {
return lengthInput / 12
} else {
return lengthInput
}
}

我想使用一个if else语句每次lengthunit == 0,但我不知道如何返回在3个不同的地方使用的3个不同的值。有没有办法缩短这个代码?或者是否有一种方法从一个if语句返回3个不同的值,然后可以在3个不同的地方使用?

让我们从使用Enum开始,而不是随机的Int值,您必须记住自己哪个是米,英寸或英尺。

enum LengthUnit {
case meter
case inch
case feet
}

var lengthUnit: LengthUnit = .meter //(or .inch, or .feet, depending on the initial unit)

现在,我们可以添加一个switch case,在Swift中,它可以处理元组:

func convert(_ value: Double, from initialUnit: LengthUnit, to targetUnit: targetUnit LengthUnit) -> Double {
switch (initialUnit, targetUnit) {
case (.meter, inch):
return value / 39.37
case (.inch, .meter):
return value * 39.37
case (.meter, .feet):
return value / 3.281
case (.feet, meter):
return value * 3.281
case (.feet, .inch):
return value / 12
case (.inch, .feet):
return value * 12
default: //It's (.inch, .inch), (.feet, .feet) and (.meter, .meter)
return value
}
}

让我们将每次重复的let lengthInput = Double(lengthIn1) + Double(lengthIn2)/100行分解为:

var combinedValues {
return Double(lengthIn1) + Double(lengthIn2)/100
}

Then,使用时:

var feetCalc: Double {
return convert(combinedValue, from: lengthUnit, to .feet)
}
var inchCalc: Double {
return convert(combinedValue, from: lengthUnit, to .inch)
}
var meterCalc: Double {
return convert(combinedValue, from: lengthUnit, to .meter)
}

现在,在foundation。framework

中已经有一个度量的转换器了

当OP要求Measurement解决方案时,我们开始吧。我借用了Larme的combinedValue属性。

var combinedValue : Double {
return Double(lengthIn1) + Double(lengthIn2)/100
}

声明lengthUnitUnitLength

let lengthUnit: UnitLength = .meters

转换方法只有一行

func convert(_ value: Double, from:  UnitLength, to:  UnitLength) -> Double {
return Measurement(value: value, unit: from).converted(to: to).value
}

三个计算属性为

var meterCalc: Double {
return convert(combinedValue, from: lengthUnit, to: .meters)
}
var inchCalc: Double {
return convert(combinedValue, from: lengthUnit, to: .inches)
}
var feetCalc: Double {
return convert(combinedValue, from: lengthUnit, to: .feet)
}

您可以返回一个字典或数组来返回多个值

最新更新