[英]Unwrapping an Optional value Swift
我要在我的webview中加载html文件。 这些文件包含对/css
和/images
子目录的引用。 因此,我从此答案中发现了以下内容。
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)
我无法解决此问题: fatal error: unexpectedly found nil while unwrapping an Optional value
在第二行fatal error: unexpectedly found nil while unwrapping an Optional value
时fatal error: unexpectedly found nil while unwrapping an Optional value
。
使用!
强制解开一个值,因此,如果它为nil
,那么您将看到致命错误。
您要使用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)
}
在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)
最大的不同是guard
模式允许您将展开的变量保持在相同的作用域中,而if let
创建新的作用域。
您应该使用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.