Unexpected Non-Void Return Value In Void Function (Swift 2.0)
Solution 1:
You have a problem because your line:
return minions
does not return from your function. Instead, it returns from the completion handler in dataTaskWithRequest
. And it shouldn't be doing so because that closure is a void function.
The problem which you have results from the fact that dataTaskWithRequest
is an asynchronous operation. Which means that it can return later after executing your function.
So, you need to change your design pattern.
One way of doing that would be the following:
static var minions:[Minion] = [] {
didSet {
NSNotificationCenter.defaultCenter().postNotificationName("minionsFetched", object: nil)
}
}
class func fetchMinionData() {
var myURL = "http://myurl/test.json"
let dataURL = NSURL(string: myURL)
let request = NSURLRequest(URL: dataURL!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
let minionJSON = JSON(data!)
var minions = [Minion]()
for (_, minionDictionary) in minionJSON {
minions.append(Minion(minionDetails: minionDictionary))
}
self.minions = minions
//THIS IS WHERE THE ERROR OCCURS
}).resume()
}
Then before calling your function you should register to listen for NSNotification
with name "minionsFetched". And only after you get that notification you should process the minions as if they were fetched.
Solution 2:
I fixed mine by creating a completion handler. You can do this instead of using notifications:
class func fetchMinionData(completionHandler: (minions: [Minion]) -> Void) {
var myURL = "http://myurl/test.json"
let dataURL = NSURL(string: myURL)
let request = NSURLRequest(URL: dataURL!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
let minionJSON = JSON(data!)
var minions = [Minion]()
for (_, minionDictionary) in minionJSON {
minions.append(Minion(minionDetails: minionDictionary))
}
completionHandler(minions: minions)
//THIS IS WHERE YOUR PREVIOUS ERROR OCCURRED
}).resume()
}