Reputation: 342
I have a function that takes an URL and returns a file URL asynchronously, when I print the value of fileURL
inside the completion
block it prints out perfectly, but the variable (fileURL
) does not retain the value outside the completion
block
FileFactory.FetchFileWithURL(workingURL, completionHandler: { (url) -> Void in
fileURL = url
print(fileURL) //prints valid URLs
})
print(fileURL) //prints nil
fileURL
is defined as:-
var fileURL:String?
How can I make sure, that fireURL
retains the value it got from completion
block?
EDIT:
Found similar question, but unfortunately it's in objc
here
Is there any equivalent of Objective-C's __block
in swift
Upvotes: 2
Views: 1076
Reputation: 10095
FetchWithURL
is an asynchronous function. fileUrl
is instantiated in the completionHandler
which itself is called only after the asynchronous task has been completed. Therefore, it simply isn't possible to use a value that doesn't exist yet.
Any operation that needs to be done with fileUrl
must be done in the same completionHandler
.
FileFactory.FetchFileWithURL(workingURL, completionHandler: { (url) -> Void in
fileURL = url
print(fileURL) //prints valid URLs
//other operations with fileURL
})
Upvotes: 0
Reputation: 24248
Call a new function inside the block. Do what you want to do with fileURL
inside the new method.
FileFactory.FetchFileWithURL(workingURL, completionHandler: { (url) -> Void in
fileURL = url
print(fileURL) //prints valid URLs
doSomethingWithFileUrl(url)
})
Upvotes: 3