如何在init Swift中在IF语句之外获取变量

时间:2018-10-29 21:47:23

标签: ios swift

如果我尝试在init外部访问变量时在if语句中设置了变量,则会收到错误消息“实例成员'friendcomparison'不能用于'User'类型”。任何帮助将不胜感激,谢谢。

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)
        }
    }

1 个答案:

答案 0 :(得分: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)
                            }
    }

只需从let中删除let friendcomparison = "yes"

并将[weak self]let friendcomparison = self?.friendcomparison一起使用