Swift getter隐式返回表达式
斯威夫特的文件说Swift getter隐式返回表达式,swift,Swift,斯威夫特的文件说 Shorthand Getter Declaration If the entire body of a getter is a single expression, the getter implicitly returns that expression. 但对于该温度转换器,会出现一个错误:预期返回“Float”的函数中缺少返回 class Temperature { var celsius: Float = 0.0 var fahrenheit: F
Shorthand Getter Declaration
If the entire body of a getter is a single expression, the getter implicitly returns that expression.
但对于该温度转换器,会出现一个错误:预期返回“Float”的函数中缺少返回
class Temperature {
var celsius: Float = 0.0
var fahrenheit: Float {
get {
((celsius * 1.8) + 32.0)
}
set {
celsius = (newValue - 32)/1.8
}
}
}
如何在getter隐式返回表达式的情况下声明此类?此表达式:
get {
((celsius * 1.8) + 32.0)
}
除非您使用的是Xcode 11/Swift 5.1,否则不会编译。如果希望代码在早期版本中编译,请显式地说return
get {
return ((celsius * 1.8) + 32.0)
}
使用Swift 5.1。。。