新Swift类中void函数中的意外非void返回值

Joe*_*oan 11 xcode ios swift

我刚开始学习面向对象,我开始编写一个用户类,它有一个计算用户与对象距离的方法.它看起来像这样:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

在上面标记的行,我收到以下错误:

(!) Unexpected non-void return value in void function
Run Code Online (Sandbox Code Playgroud)

我在别处寻找解决方案,但似乎找不到任何适用于此实例的内容.我在其他地方使用了distanceFromLocation代码,并且它运行正常,所以我不确定在这种情况下的用法有什么不同.

谢谢你的帮助!

OOP*_*Per 32

您在方法标题中缺少返回类型.

func calculateDistance(location: CLLocation) -> CLLocationDistance {
Run Code Online (Sandbox Code Playgroud)

看起来我的答案看起来是次要的重复,所以有些补充.

声明没有返回类型的函数(在这种情况下包括方法)被称为void函数,因为:

func f() {
    //...
}
Run Code Online (Sandbox Code Playgroud)

相当于:

func f() -> Void {
    //...
}
Run Code Online (Sandbox Code Playgroud)

通常,您不能从此类void函数返回任何值.但是,在Swift中,你只能返回一个值(我不确定它可以被称为"值"),"void value"代表().

func f() {
    //...
    return () //<- No error here.
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以理解错误消息的含义:

void函数中的意外非void返回值

您需要更改返回值,否则将返回类型更改为Void其他类型.