【问题标题】:How does throw declare throughs 'startAccessingSecurityScopedResource()' in Swift?throw 如何在 Swift 中通过'startAccessingSecurityScopedResource()' 声明?
【发布时间】:2019-09-10 13:47:51
【问题描述】:

我会通过当前文件选择器导入数据。我正在查看开发文档并遵循它,并且存在一个问题。当我不在警卫的条件语句中时,我将收到一个错误,但 'throw' 不可用。你如何解决这个问题?

func startAccessingSecurityScopedResource() -> Bool

用法

    func presentDocument(at documentURL: URL) {


        // Start accessing a security-scoped resource.
        guard documentURL.startAccessingSecurityScopedResource() else {
            throw IXError.fileAcessFailed // Error is not handled because the enclosing function is not declared 'throws'
            return
        }

由于未声明封闭函数,因此未处理错误 '投掷'

我尝试了guard let,但失败了。

        guard let Acess = documentURL.startAccessingSecurityScopedResource() else { //Initializer for conditional binding must have Optional type, not 'Bool'
            throw IXError.fileAcessFailed // Error is not handled because the enclosing function is not declared 'throws'
            return
        }

IXError

public enum IXError: Error {
    ...
}

************************************编辑开始 ************* *************************************

我根据答案添加了throws,但是使用它的函数出错了。

    func documentBrowser(_ controller: UIDocumentBrowserViewController, didPickDocumentURLs documentURLs: [URL]) {
        guard let sourceURL = documentURLs.first else { return }
        presentDocument(at: sourceURL) // Call can throw, but it is not marked with 'try' and the error is not handled
    }
...
    func documentBrowser(_ controller: UIDocumentBrowserViewController, didImportDocumentAt sourceURL: URL, toDestinationURL destinationURL: URL) {
        presentDocument(at: destinationURL) // Call can throw, but it is not marked with 'try' and the error is not handled
    }
...
    func presentDocument(at documentURL: URL) throws {

        guard documentURL.startAccessingSecurityScopedResource() else {
            throw IXError.fileAcessFailed
            return
        }

Error 是 Call 可以抛出,但没有标上 'try' 和错误 不处理

【问题讨论】:

    标签: ios swift guard


    【解决方案1】:

    错误未处理,因为封闭函数未声明为“抛出”

    这是指您的presentDocument 函数。像这样声明它:

    func presentDocument(at documentURL: URL) throws {
    ...
    }
    

    【讨论】:

    • 这将导致在使用此函数时出错。 '调用可以抛出,但它没有用'try'标记并且错误没有在其他函数中处理'
    • 你需要将调用包装在一个 do/catch 块中。
    • 哦,我明白了@Gereon 那么,我应该在流行语中放什么?
    • 处理抛出的错误所需的任何代码。
    • 如何将导入文件路径中的数据放入对象中?
    猜你喜欢
    • 2014-07-27
    • 1970-01-01
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    • 2014-01-22
    • 1970-01-01
    相关资源
    最近更新 更多