0

If I set the variable inside the if statement when I try to access the variable outside on the init I get the error "Instance member 'friendcomparison' cannot be used on type 'User'". Any help would be appreciated, thank you.

let friendcomparison: String

func getfriendname() {
    if frienddeeper == Auth.auth().currentUser?.uid {
        let friendcomparison = "yes"
    }
    let link = URL.init(string: credentials["profilePicLink"]!)
    URLSession.shared.dataTask(with: link!, completionHandler: { (data, response, error) in
        if error == nil {
            let profilePic = UIImage.init(data: data!)
            let user = User.init(name: name, username: username, email: email, id: id, friendstatus: friendcomparison, token: token!, profilePic: profilePic!)
            completion(user)
        }
    }
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Jacob Zyla
  • 225
  • 2
  • 11
  • Possible duplicate of [Can Swift return value from an async Void-returning block?](https://stackoverflow.com/questions/28390635/can-swift-return-value-from-an-async-void-returning-block). You are missing the idea of asynchronicity. – Dávid Pásztor Oct 29 '18 at 21:49
  • This is a bit hard to follow. Are you able to include more code? E.g. classes and initialisers? – Jordan Johnson Oct 29 '18 at 22:04

1 Answers1

0
    func getfriendname() {
        if frienddeeper == Auth.auth().currentUser?.uid {
                           friendcomparison = "yes"
                        }
                        let link = URL.init(string: credentials["profilePicLink"]!)
                        URLSession.shared.dataTask(with: link!, completionHandler: { [weak self] (data, response, error) in
                            if error == nil {
                                let profilePic = UIImage.init(data: data!)
let friendcomparison = self?.friendcomparison
                                let user = User.init(name: name, username: username, email: email, id: id, friendstatus: friendcomparison, token: token!, profilePic: profilePic!)
                                completion(user)
                            }
    }

Just remove let from let friendcomparison = "yes"

and use [weak self] with let friendcomparison = self?.friendcomparison

Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
  • @DávidPásztor i've fixed the answer. He obviously can capture the environment using [weak self] – Vyacheslav Oct 29 '18 at 22:09
  • @DávidPásztor where friendcomparison is returned? `friendcomparison = "yes"` works synchronously. `if frienddeeper == Auth.auth().currentUser?.uid` check checks the value. `dataTask ` just consumes this value. – Vyacheslav Oct 29 '18 at 22:14
  • What is `completion`? – rmaddy Oct 29 '18 at 22:14
  • @rmaddy this is part of the code is from the question. I think the topic starter just removed some parts of the code. – Vyacheslav Oct 29 '18 at 22:16