Swift中关键字“ throws”是什么意思?

问题描述 投票:-1回答:2

这里“ throws”关键字的含义是:

“”

此代码需要花费很长时间才能执行,我认为上图中的“ throws”关键字相关:

let url = URL(string:"\(APIs.postsImages)\(postImg)")
let imgData = try? Data.init(contentsOf: url)
self.postImage.image = UIImage.init(data: imgData)
swift syntax nsdata nsurl
2个回答
4
投票

init() throws可以返回有关失败的更多信息,并让调用者决定是否关心它。阅读有关它的有用文章here

为了表明函数,方法或初始化程序可能引发错误,您需要在函数的参数后的声明中写入throws关键字。标有throws的功能称为throwing function。如果该函数指定了返回类型,则将throws关键字写在返回箭头之前。

func thisFunctionCanThrowErrors() throws -> String

或在实际代码中,可能看起来像这样:

enum PossibleErrors: Error {
    case wrongUsername
    case wrongPassword
}

func loggingIn(name: String, pass: String) throws -> String {

    if name.isEmpty { 
        throw PossibleErrors.wrongUsername 
    }
    if pass.isEmpty { 
        throw PossibleErrors.wrongPassword 
    }
    return "Fine"
}

必须使用以下尝试运算符之一来调用类似throwing functions的代码:

  • try
  • 尝试?
  • 尝试!

使用init() throws,您可以中断类初始化程序的执行,而无需填充所有存储的属性:

class TestClass {

    let textFile: String

    init() throws {
        do {
            textFile = try String(contentsOfFile: "/Users/swift/text.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/text.txt", 
                                    encoding: NSUTF8StringEncoding)
    }
}

2
投票

throws关键字表示函数可能会引发错误。也就是说,它是throwing function。有关更多详细信息,请参见the documentation

© www.soinside.com 2019 - 2024. All rights reserved.