[英]an error during a type conversion in Swift 3
我正在学习Swift动画。 它的材料是用Swift 2编写的,所以我不得不将其原始代码转换为Swift3。我从中学到了很多,但是现在我遇到了一个大问题。 Xcode成功构建了此代码,但产生了运行时错误消息。 (我附加了图像文件。)
我完全无法解决这个问题,因为我觉得我经验不足。 我怎样才能解决这个问题? 救命。
func setQuote() {
//fadeOut
//getting data from API
let dataService = DataService()
dataService.getQuoteData {(quote, author) -> Void in
UIView.animate(withDuration: 0.5, animations: {
//fadeIn and backgroundColor
//quote
self.quoteLabel.text = quote
//author - optional binding
//if no author
}, completion:nil)
}
}
class DataService {
func getQuoteData(_ completion: @escaping (_ quote: String, _ author: String?) -> ()) {
let url = URL(string: "http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json")!
URLSession.shared.dataTask(with: url, completionHandler: { ( data: Data?, response: URLResponse?, error: NSError?) -> Void in
do {
let jsonDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
let aQuote = jsonDictionary["quoteText"] as! String
let aAuthor = jsonDictionary["quoteAuthor"] as! String
DispatchQueue.main.async(execute: { () -> Void in
completion(aQuote, aAuthor)
})
} catch {
print("invalid json query")
}
} as! (Data?, URLResponse?, Error?) -> Void).resume()
}
}
您可以尝试像这样重写它
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
do {
let jsonDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
let aQuote = jsonDictionary["quoteText"] as! String
let aAuthor = jsonDictionary["quoteAuthor"] as! String
DispatchQueue.main.async(execute: { () -> Void in
completion(aQuote, aAuthor)
})
} catch {
print("invalid json query")
}
}
task.resume()
或简单地将( data: Data?, response: URLResponse?, error: NSError?) -> Void
更改为( data, response, error) -> Void
并删除as! ...
as! ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.