[英]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.