简体   繁体   English

展开一个可选值Swift

[英]Unwrapping an Optional value Swift

I am to load html file in my webview. 我要在我的webview中加载html文件。 The files contain references to /css and /images sub directories. 这些文件包含对/css/images子目录的引用。 So, I found the following from this answer . 因此,我从此答案中发现了以下内容。

    let path: String? = NSBundle.mainBundle().pathForResource("Ace-VetBolus", ofType: "html", inDirectory: "HTMLFiles")
    let requestURL = NSURL(string:path!);
    let request = NSURLRequest(URL:requestURL!);

    web1.loadRequest(request)

And I cannot resolve this issue: fatal error: unexpectedly found nil while unwrapping an Optional value at the second line. 我无法解决此问题: fatal error: unexpectedly found nil while unwrapping an Optional value在第二行fatal error: unexpectedly found nil while unwrapping an Optional valuefatal error: unexpectedly found nil while unwrapping an Optional value

Using ! 使用! forcefully unwraps a value, so if it's nil , you're going to get a fatal error as you see. 强制解开一个值,因此,如果它为nil ,那么您将看到致命错误。

You want to use an if let statement or a guard statement. 您要使用if let语句或guard语句。

let path: String? = NSBundle.mainBundle().pathForResource("Ace-VetBolus", ofType: "html", inDirectory: "HTMLFiles")
if let unwrappedPath = path {
    let requestURL = NSURL(string: unwrappedPath)
    let request = NSURLRequest(URL: requestURL)

    web1.loadRequest(request)
}

Using guard in Swift 2 functions like so: 在Swift 2中使用guard功能如下:

let path: String? = NSBundle.mainBundle().pathForResource("Ace-VetBolus", ofType: "html", inDirectory: "HTMLFiles")
guard let unwrappedPath = path else {
    return // or handle fail case some other way
}
let requestURL = NSURL(string: unwrappedPath)
let request = NSURLRequest(URL: requestURL)
web1.loadRequest(request)

Biggest different is the guard pattern allows you to keep the unwrapped variable in the same scope, while if let creates a new scope. 最大的不同是guard模式允许您将展开的变量保持在相同的作用域中,而if let创建新的作用域。

You should use NSBundle method URLForResource: 您应该使用NSBundle方法URLForResource:

if let url = NSBundle.mainBundle().URLForResource("Ace-VetBolus", withExtension: "html", subdirectory: "HTMLFiles") {
    let requestURL = NSURLRequest(URL: url)
    web1.loadRequest(requestURL)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM