(Swift) 尝试加载本地 .css 文件时出错
(Swift) Error when trying to load a local .css file
在我的应用程序中,我有一个名为 "CSS"
的文件夹,其中包含名为 "style.css"
的文件。
当我尝试加载它时,出现此错误:
Fatal error: Unexpectedly found nil while unwrapping an Optional value
这是我尝试加载它的代码:
let path = Bundle.main.path(forResource: "style", ofType: "css", inDirectory: "CSS")!
let cssString = try! String(contentsOfFile: path).trimmingCharacters(in: .whitespacesAndNewlines)
确保您的文件存在于“构建阶段”>“复制捆绑资源”列表中
不要强制解包,检查这样的错误
guard Bundle.main.path(forResource: "style", ofType: "CSS") != nil else {
return
}
do {
} catch let error {
print(error)
}
在我的应用程序中,我有一个名为 "CSS"
的文件夹,其中包含名为 "style.css"
的文件。
当我尝试加载它时,出现此错误:
Fatal error: Unexpectedly found nil while unwrapping an Optional value
这是我尝试加载它的代码:
let path = Bundle.main.path(forResource: "style", ofType: "css", inDirectory: "CSS")!
let cssString = try! String(contentsOfFile: path).trimmingCharacters(in: .whitespacesAndNewlines)
确保您的文件存在于“构建阶段”>“复制捆绑资源”列表中
不要强制解包,检查这样的错误
guard Bundle.main.path(forResource: "style", ofType: "CSS") != nil else {
return
}
do {
} catch let error {
print(error)
}