0

so i have this code here

    let url = URL(string: APILink)!

    let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
        guard let data = data else { return }
        let response = String(data: data, encoding: .utf8)!
        print(response)
    }
    task.resume()
}

i was wondering how i could make response here public to other functions? using the public keyword when declaring response doesnt work (of course)

1 Answers1

0

The issue is not that response is private, but that it is a local variable. It is similar to

func foobar() {
  let x = 3 // local variable, no one else can access this!
}

the simplest solution is to figure out where else you want access to that variable and pass it as a parameter

func needsX(passedInX x: Int) {
  // do something with x
}

func foobar() {
  let x = 3 // local variable, no one else can access this!
  needsX(passedInX: x) // now it can access x
}

Alternatives to passing it as a parameter would be to save in another variable which has a broader scope, for example an instance variable (if you are inside a class)

func foobar() {
  let x = 3 // local variable, no one else can access this!
  self.x = 3 // now any method in this instance can access it via self.x
}
Max
  • 21,123
  • 5
  • 49
  • 71