gpt4 book ai didi

ios - Swift 3 类型转换期间的错误

转载 作者:行者123 更新时间:2023-11-29 00:19:54 25 4
gpt4 key购买 nike

我正在学习 Swift 动画。它的素材是用Swift 2写的,所以我不得不把它的原始代码转换成Swift 3。我一直在学习它,但现在我遇到了一个大问题。 Xcode 成功构建了此代码,但产生了运行时错误消息。 (I attached the image file.)

我自己根本无法解决这个问题,我想我经验不足。我怎样才能解决这个问题?帮助。

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! ...

关于ios - Swift 3 类型转换期间的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44380954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com