Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

ios - unexpected non-void return value in void function in new Swift class

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.

Thanks for any help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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 ().

func f() {
    //...
    return () //<- No error here.
}

Now, you can understand the meaning of the error message:

unexpected non-void return value in void function

You need to change the return value or else change the return type Void to some other type.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...