【发布时间】:2019-03-19 19:31:25
【问题描述】:
以下代码:
protocol ExampleProtocol {
var simpleDescription: String { get }
var absoluteValue: Double { get }
mutating func adjust()
}
extension Double: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
var absoluteValue: Double {
if self < 0 {
return self * -1
} else if self > 0 {
return self
}
}
mutating func adjust() {
self += 42
}
}
当尝试使用 simpleDescription 或 absoluteValue 执行它时(例如 print(10.simpleDescription),我只是得到这个错误:
预期会返回“Double”的函数中缺少返回
absoluteValue “函数”返回自身,所以 Double 值,为什么说它缺少一个?
【问题讨论】:
-
想想
self == 0的情况。 -
您可能只想将
else if self > 0更改为else。 -
@rmady 非常感谢 - 添加了 else { return 0 },但是如果 self == 0 我怎么能写一个 else 呢?因为如果我添加“else if self == 0”,它会抛出一个错误?