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

标签 ios swift

如果我在 if 语句内设置变量,当我尝试访问 init 外部的变量时,我会收到错误“实例成员 '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)
        }
    }

最佳答案

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

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

并使用[weak self]letfriendcomparison = self?.friendcomparison

关于ios - 如何在 init Swift 中获取 IF 语句之外的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53054329/

相关文章:

ios - 可以在没有 DEP 的情况下强制 iOS 更新 OTA 吗?

ios - 从 iOS 上的两个不同应用程序访问相同的文件

ios - 如何使用 swift 在 ios 设备上发送自动电子邮件?

objective-c - 如何在 iOS 5 运行时上 stub /注入(inject) View Controller 以进行基于状态的测试?

swift - 没有 '+"候选人产生预期的上下文结果类型 'AnyObject' Swift 3 中的错误

从 UIWebView 调用 Swift 的 Javascript

ios - Swift:如何从函数返回类类型

ios - 表删除操作删除单元格内容而不是单元格本身?

ios - 移动谷歌地图但不像优步那样移动标记

swift - 将其设置为变量时是否执行闭包?