-5
func isEmailTaken(email:String) -> String {
    let myUrl = URL(string: "URL");
    var request = URLRequest(url:myUrl!)
    request.httpMethod = "POST"
    let postString = "email=\(email)";
    request.httpBody = postString.data(using: String.Encoding.utf8);
    let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
        if error != nil {
            print("error=\(error)")
            return
        }
        print("response = \(response)")
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

            if let parseJSON = json {
                let emailAlreadyTakenData = parseJSON["emailAlreadyTaken"] as! String
                print(emailAlreadyTakenData)

            }
        } catch {
            print(error)
        }
    }
    task.resume()

    return(emailAlreadyTakenData)
}

The line :

return(emailAlreadyTakenData)

Doesnt get the variable value. So, the http request gets the data successfully but the return command doesn't parse the correct data.

jscs
  • 63,694
  • 13
  • 151
  • 195
sam yellow
  • 31
  • 3
  • Have a look into asynchronous methods... The network response returns a value asynchronously, so you can't use a normal synchronous `return` statement, you have to use a completion handler. Unrelated, but when returning a value in Swift, there's no need for the brackets. – Dávid Pásztor Jan 07 '18 at 21:14
  • ... and why do you cast `.mutableContainers` to an immutable dictionary? – vadian Jan 07 '18 at 21:17
  • @vadian `.mutableContainers` won't have any effect, since the variable is declared as being immutable anyways. I think the more pressing issue about that line is, why cast to `NSDictionary` instead of `Dictionary`. – Dávid Pásztor Jan 07 '18 at 21:26
  • 1
    @DávidPásztor `.mutableContainers` has no effect in Swift at all. I forgot the smiley. Unfortunately most tutorials suggest that nonsense. – vadian Jan 07 '18 at 21:28

1 Answers1

1

Your variable is in different scope, then when you declared it. So you cannot access the variable outside of the defined scope

DZDomi
  • 1,685
  • 15
  • 13
  • 2
    Even though that's the intermediate issue, solving the scoping problem wouldn't make OP's code work. The more pressing issue is the issue of using a `return` statement in an asynchronous function... – Dávid Pásztor Jan 07 '18 at 21:16
  • of course you are right, this is the next issue – DZDomi Jan 07 '18 at 21:18