So I am having an issue where the following is now throwing an error Non-void function should return a value
func newsfetch() -> [News]{
var tempNews: [News] = []
let jsonURLString = "https://api.drn1.com.au/api-access/news"
guard let feedurl = URL(string: jsonURLString) else { return } // ERROR: Non-void function should return a value
URLSession.shared.dataTask(with: feedurl) { (data,response,err)
in
guard let news = data else { return }
do{
let newsdata = try JSONDecoder().decode(NewsData.self, from: news)
print(newsdata.news)
newsdata.news.forEach(){
// print($0.title)
tempNews.append(News(title: $0.title))
}
}catch let jsonErr{
print("error json ", jsonErr)
}
}.resume()
return tempNews
}
I am unsure why this has happened as I took the JSON feed script from our now playing function and it works like a charm.
the only difference is @obj is not at the front of this func because it causes an error with the -> [news] command.
When you use return
it means exit the function without doing anything. Obviousely your function needs to return [News]
. There are two way to fix it:
guard let feedurl = URL(string: jsonURLString) else { return [News]()}
or make your function:
func newsfetch() -> [News]?
The later needs special care when you call that function. You most probably need optional chaining or force unwrapping(Not recommended)
Change return to return(tempNews) Because you are returning null where a type of [News] expected
Proper statement
else { return tempNews}
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.