这里“throws”字的含义是什么:
这段代码需要很长时间才能执行,我认为在相关的图片中“抛出”关键字
let url = URL(string:"\(APIs.postsImages)\(postImg)")
let imgData = try? Data.init(contentsOf: url)
self.postImage.image = UIImage.init(data: imgData)
答案 0 :(得分:3)
init() throws
可以返回有关失败的更多信息,让调用者决定他们是否关心失败。
阅读这篇有用的帖子:here。
要指示函数,方法或初始化程序可以抛出错误,您需要在函数声明后面的参数中写入throws
关键字。标有throws
的函数称为投掷函数。如果函数指定了返回类型,则在返回箭头(->)
之前编写throws关键字。
func thisFunctionCanThrowErrors() throws -> String
使用init() throws
,您可以打破类初始化程序的执行,而无需填充所有存储的属性:
class TestClass {
let textFile: String
init() throws {
do {
textFile = try String(contentsOfFile: "/Users/swift/someText.txt", encoding: NSUTF8StringEncoding)
catch let error as NSError {
throw error
}
}
}
在结构中,您甚至可以避免do/catch
阻止:
struct TestStruct {
var textFile: String
init() throws {
textFile = try String(contentsOfFile: "/Users/swift/someText.txt", encoding: NSUTF8StringEncoding)
}
}
答案 1 :(得分:2)
throws
关键字表示函数可能会抛出错误。即,它是投掷功能。有关其他详细信息,请参阅the documentation。