ios 新 Swift 类中的 void 函数中的意外非 void 返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38469648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
unexpected non-void return value in void function in new Swift class
提问by Joe Sloan
I'm just starting to learn about Object Oriented, and I've begun writing up a user class that has a method for calculating the user's distance from an object. It looks like this:
我刚刚开始学习面向对象,并且我已经开始编写一个用户类,该类具有用于计算用户与对象的距离的方法。它看起来像这样:
class User{
var searchRadius = Int()
var favorites : [String] = []
var photo = String()
var currentLocation = CLLocation()
func calculateDistance(location: CLLocation){
let distance = self.currentLocation.distanceFromLocation(location)*0.000621371
return distance //Error returns on this line
}
}
At the line marked above, I get the following error:
在上面标记的行中,我收到以下错误:
(!) Unexpected non-void return value in void function
I've looked elsewhere for a solution, but can't seem to find anything that applies to this instance. I've used the distanceFromLocation code elsewhere, and it's worked okay, so I'm not sure what's different about the usage in this case.
我在别处寻找解决方案,但似乎找不到任何适用于此实例的内容。我已经在其他地方使用了 distanceFromLocation 代码,它工作正常,所以我不确定这种情况下的用法有什么不同。
Thanks for any help!
谢谢你的帮助!
回答by OOPer
You are missing return type in your method header.
您的方法标头中缺少返回类型。
func calculateDistance(location: CLLocation) -> CLLocationDistance {
Seemingly my answer looks as an inferior duplicate, so some addition.
似乎我的答案看起来是次等的重复,所以要补充一些。
Functions (including methods, in this case) declared without return types are called as void function, because:
没有返回类型声明的函数(包括方法,在这种情况下)被称为 void 函数,因为:
func f() {
//...
}
is equivalent to:
相当于:
func f() -> Void {
//...
}
Usually, you cannot return any value from such void functions.
But, in Swift, you can return only one value (I'm not sure it can be called as "value"), "void value" represented by ()
.
通常,您不能从此类 void 函数返回任何值。但是,在 Swift 中,您只能返回一个值(我不确定它是否可以称为“值”),由()
.
func f() {
//...
return () //<- No error here.
}
Now, you can understand the meaning of the error message:
现在,您可以理解错误消息的含义:
unexpected non-void return value in void function
void 函数中的意外非 void 返回值
You need to change the return value or else change the return type Void
to some other type.
您需要更改返回值或将返回类型更改为Void
其他类型。
回答by Duncan C
Your function calculateDistance does not specify a return value. That means it does not return anything.
您的函数 calculateDistance 未指定返回值。这意味着它不会返回任何东西。
However, you have a line return distance
, which isreturning a value.
但是,您有一个 line return distance
,它正在返回一个值。
If you want your function to return a distance, you should declare it like this:
如果你想让你的函数返回一个距离,你应该像这样声明它:
func calculateDistance(location: CLLocation) -> CLLocationDistance
{
//your code
return distance
}