简体   繁体   中英

Swift Function Error: 'Float' is not convertible to 'Void'

I have the following function, which generates a quick NSURLConnection request and returns the contents of the page. The function gives me an error on my return line 'Float' is not convertible to 'Void'

func getDJI(year: Int, month: Int, day: Int) -> Float {
    let baseURL = "http://geo.crox.net/djia"

    var request = NSMutableURLRequest(URL: NSURL(string: String(format:"%@/%02d/%02d/%02d",baseURL, year, month, day))!)
    httpGet(request){
        (data, error) -> Void in
        if error != nil {
            println(error)
        } else {
            return (data as NSString).floatValue
        }
    }
}

What is going wrong?

There are two problems here.

First, you've got a closure which is supposed to return Void and you're trying to return a Float from it, and second, you've got a function that is supposed to return a Float , but you never return anything from it.

What might make the most sense is for your outer function to return Void , and for it to accept a closure that expects a Float and returns Void :

func getDJI(year: Int, month: Int, day: Int, completion:(Float)->Void) -> Void {
    let baseURL = "http://geo.crox.net/djia"

    var request = NSMutableURLRequest(URL: NSURL(string: String(format:"%@/%02d/%02d/%02d",baseURL, year, month, day))!)
    httpGet(request){
        (data, error) -> Void in
        if error != nil {
            println(error)
        } else {
            completion((data as NSString).floatValue)
        }
    }
}

And for the record... (data as NSString).floatValue looks pretty suspicious to me...

Your return is inside your httpGet() closure, which is supposed to return nothing ("Void").

This looks like you're trying to take an asynchronous httpGet() function and treat it as a synchronous function. You can't do that. I don't know what httpGet() does, but it's pretty obvious that it returns immediately and calls its closure when data is downloaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM