ecfedele
ecfedele

Reputation: 316

Issue returning NSURL in Swift

Alright folks, I'm trying to write a segment that formats a NSURL from NSDictionary parts for an OAuth 2.0 authentication body. The issue is that I cannot return the NSURL that I generate.

private func formAuthURL ((Void) -> NSURL)
{
    // Declare the base part of the URL:
    var AuthURLString : String = "https://accounts.google.com/o/oauth2/auth?";

    // Now, space-delimit the scopes and redirect URL - this works by replacing " " with "%20"
    // and others in accordance with standard URL practice:
    self.AuthScope    = self.AuthScope?.stringByReplacingOccurrencesOfString (" ", withString: "%20", options: nil, range: nil);
    self.AuthScope = self.AuthScope?.stringByReplacingOccurrencesOfString (":", withString: "%3A", options: nil, range: nil);
    self.AuthScope = self.AuthScope?.stringByReplacingOccurrencesOfString ("/", withString: "%2F", options: nil, range: nil);
    self.AuthRedirect = self.AuthRedirect?.stringByReplacingOccurrencesOfString (":", withString: "%3A", options: nil, range: nil);
    self.AuthRedirect = self.AuthRedirect?.stringByReplacingOccurrencesOfString ("/", withString: "%2F", options: nil, range: nil);

    // Now, format the Client ID and other variables into parts:
    let loc_ClientID = "client_id=\(self.ClientID)";
    let loc_Redirect = "redirect_uri=\(self.AuthRedirect)";
    let other_parts  = "response_type=code&access_type=offline";

    // Combine, format into URL, and return:
    AuthURLString    = AuthURLString + loc_ClientID + loc_Redirect + self.AuthScope! + other_parts;
    var AuthURL      = NSURL (string: AuthURLString);
    return AuthURL;
}

I've also tried concatenating the return statement (i.e. return NSURL (string: AuthURLString) to no avail. The error it generates is as follows:

Cannot convert the expression's type 'NSURL?' to type '()'.

I'm dead stumped on what this error means. It seems like some sort of optional, but I've tried changing the function return type (that is, ((Void) -> NSURL?) and I still can't get it to work. The whole concept of optionals and unwrapping and what not is something I still don't grasp very well, so if this is a primitive question, forgive me.

Upvotes: 0

Views: 248

Answers (1)

67cherries
67cherries

Reputation: 6951

Replace this:

private func formAuthURL ((Void) -> NSURL)

With this:

private func formAuthURL() -> NSURL

Here is the basic form of function declarations in swift:

func functionName(paramName:ParamType) -> ReturnType

Based on this you can see that your function was trying to take a closure with the form (Void) -> NSURL and returns nothing (if you don't give a return type using -> ReturnType it assumes you return nothing).

You can read more about functions in swift here.

Upvotes: 1

Related Questions