我正在为我正在制作的应用程序制作一个转换脚本,并且想为我制作的所有不同的转换结构制作一个协议。我希望它们都有一个名为
unitType
的属性,一个名为 amount
的属性,以及一个名为 convert(to otherType) -> Double
的变异函数。这是代码:
public class Units {
enum TemperatureUnits {
case fahrenheit, rankine
case celsius, kelvin
}
enum DistanceUnits {
case inch, foot, yard, mile
case millimeter, centimeter, meter, kilometer
}
//Plus any others I decide to do
}
//Want to create a protocol here
protocol Conversion {
var unitType
var amount: Double
func convert(to otherType) -> Double
}
//This struct works, but i want to implement the protocol
public struct Temperature {
var unitType: Units.TemperatureUnits
var amount: Double
mutating func convert(to otherType: Units.TemperatureUnits) -> Double {
var returnAmount: Double
switch otherType {
case .fahrenheit:
switch unitType {
case .fahrenheit:
returnAmount = amount
case .celsius:
returnAmount = (amount * (9/5)) + 32
case .kelvin:
returnAmount = (amount - 273.15) * (9/5) + 32
case .rankine:
returnAmount = amount - 459.67
}
case .celsius:
switch unitType {
case .celsius:
returnAmount = amount
case .kelvin:
returnAmount = amount - 273.15
case .fahrenheit:
returnAmount = (amount - 32) * (5/9)
case .rankine:
returnAmount = (amount - 491.67) * (5/9)
}
case .kelvin:
switch unitType {
case .fahrenheit:
returnAmount = (amount - 32) * (5/9) + 273.15
case .celsius:
returnAmount = amount + 273.15
case .kelvin:
returnAmount = amount
case .rankine:
returnAmount = amount * (5/9)
}
case .rankine:
switch unitType {
case .rankine:
returnAmount = amount
case .fahrenheit:
returnAmount = amount + 459.67
case .celsius:
returnAmount = (amount * (9/5)) + 491.67
case .kelvin:
returnAmount = amount * (9/5)
}
}
unitType = otherType
amount = returnAmount
return returnAmount
}
}
现在,就像我说的那样,当我尝试制定一个多个这些结构可以遵守的协议时,问题就来了。我将枚举封装在
Units
类中的全部原因是为了让它们有条理,并看看我是否可以使协议像这样工作:
protocol Conversion {
var unitType: Units { get set }
var amount: Double { get set }
func convert(to otherType: Units) -> Double
}
然后像这样实现它:
public struct Temperature: Conversion {
var unitType: Units.TemperatureUnits
var amount: Double
mutating func convert(to otherType: Units.TemperatureUnits) -> Double {
//code
}
}
public struct Distance: Conversion {
var unitType: Units.DistanceUnits
var amount: Double
mutating func convert(to otherType: Units.DistanceUnits) -> Double {
//code
}
}
但它不起作用。我想知道我是否能够快速创建具有这种灵活性的协议,或者是否有必要在这种情况下创建协议。 (此外,嵌套的 switch 语句是我能找到的应用转换的最有效方法——我确信有更有效的方法,但我就是想不出来。)