Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在返回函数中处理可能的零?_Ios_Swift_Return - Fatal编程技术网

Ios 在返回函数中处理可能的零?

Ios 在返回函数中处理可能的零?,ios,swift,return,Ios,Swift,Return,我有一个func,我想在其中返回一个已配置的UIDocumentInteractionController 问题是,如果我不能构造文档URL,我想返回,但不能,因为func需要返回查看器。如何编辑此函数,使func在URL有效或不存在时返回查看器 func saveBase64StringToPDF(base64String: String, title: String) -> UIDocumentInteractionController { guard var document

我有一个func,我想在其中返回一个已配置的
UIDocumentInteractionController

问题是,如果我不能构造文档URL,我想返回,但不能,因为func需要返回查看器。如何编辑此函数,使func在URL有效或不存在时返回查看器

func saveBase64StringToPDF(base64String: String, title: String) -> UIDocumentInteractionController {
    guard var documentsURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last,
          let convertedData = Data(base64Encoded: base64String)
        else {
            return // issue is here
    }

    documentsURL.appendPathComponent(title)

    do {
        try convertedData.write(to: documentsURL)
    } catch {
        print("FAILED TO WRITE")
    }
    let interactionController = UIDocumentInteractionController(url: documentsURL)
    return interactionController
}

您应该将返回值设置为可选

func saveBase64StringToPDF(base64String: String, title: String) -> UIDocumentInteractionController? {
    guard var documentsURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last,
          let convertedData = Data(base64Encoded: base64String)
        else {
            return nil
        }
    }

    documentsURL.appendPathComponent(title)

    do {
        try convertedData.write(to: documentsURL)
    } catch {
        print("FAILED TO WRITE")
    }

    let interactionController = UIDocumentInteractionController(url: documentsURL)
    return interactionController
}

在方法声明的返回类型中使用
UIDocumentInteractionController?
,而不是
UIDocumentInteractionController


任何类或对象旁边的
告诉编译器它是可选的。可选值可以包含值或nil

只需在as func saveBase64StringToPDF(base64String:String,title:String)->UIDocumentInteractionController?上进行函数抛出,并抛出正确的错误,解释失败的原因。