简体   繁体   中英

How do I get the variable out of the local scope and be able to use that variable in another view or other functions in Swift, Xcode?

How do I get the variable 'model' out of the local scope and be able to use that variable in another view or other functions?

class LoginModel {
    
    weak var delegate: Downloadable?
    let networkModel = Network()
    func downloadLogin(parameters: [String: Any], url: String) {

        
        let request = networkModel.request(parameters: parameters, url: url)
        networkModel.response(request: request) { (data) in
            let model = try! JSONDecoder().decode([Login].self,from: data)
            
            DispatchQueue.main.async(execute: { () -> Void in
                print(model) //data shows
            })
            
            self.delegate?.didReceiveData(data: model)
            
        }
        print(model) //data doesn't show
    }
}

The reason why you can't access the model constant is that your model was declared in a function with lower hierarchy than where the print function is located.

The way Swift variables work is that they can only be accessed on any sub-class/function/method with a lower hierarchy than itself (ie variables declared inside a function cannot be used outside the function itself).

To be able to access your model variable anywhere in every swift file in your project, you should use a global variable, which is defined by the official Swift programming guide as:

Variables that are defined outside of any function, method, closure, or type context. Global constants and variables are always computed lazily.

Which means to say that to make model a global variable, you should declare it outside of your LoginModel class, or any other similar classes, functions, methods, closures, or type contexts.

If you do not need to access model everywhere but just need to print it, you can either move your print function into the networkModel.response function, or declare your model constant outside of the networkModel.response function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM