Ios Swift 3中的类型转换期间出错
我在学斯威夫特动画。它的资料是用Swift 2编写的,所以我不得不将它的原始代码转换成Swift 3。我从中学到了很多,但现在我有一个大问题。Xcode成功生成了此代码,但生成了运行时错误消息 我一个人根本解决不了这个问题,因为我想我没有什么经验。我怎样才能解决这个问题?救命啊Ios Swift 3中的类型转换期间出错,ios,swift3,Ios,Swift3,我在学斯威夫特动画。它的资料是用Swift 2编写的,所以我不得不将它的原始代码转换成Swift 3。我从中学到了很多,但现在我有一个大问题。Xcode成功生成了此代码,但生成了运行时错误消息 我一个人根本解决不了这个问题,因为我想我没有什么经验。我怎样才能解决这个问题?救命啊 func setQuote() { //fadeOut //getting data from API let dataService = DataService() dataSer
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()
或者简单地将
(数据:数据?、响应:URLResponse?、错误:NSError?)->Void
更改为(数据、响应、错误)->Void
,并将作为!删除代码>U是否缺少括号?应该是((数据?、URLResponse?、错误?->Void)
否。打开的括号从“URLSession.shared.dataTask”开始(“为什么需要as!(数据?、URLResponse?、错误?)->Void
无论如何?你可以删除它并使用.resume()我不能。当我删除它时,Xcode说,无法转换类型的值”(数据?、URLResponse?、NSError?)->Void'to expected argument type'(Data?、URLResponse?、Error?->Void'Fix:Insert“as!(Data?、URLResponse?、Error?)->Void”1.哪一行生成了错误?2.在控制台中,总是有一行传达了更有意义的原因…您只需向上滚动并找到并粘贴infoOMG..谢谢,Tj3n.)你让我开心。我会继续努力,像你一样帮助别人。