我使用路径文档链接app中的外部文件。但是当我想在真正的iPhone上运行项目时,我用NSBundle替换了路径。现在我因为NSBundle(我认为)或其他原因而收到错误。我该如何调试呢?
控制台中的错误:fatal error: unexpectedly found nil while unwrapping an Optional value
整个代码:
import UIKit
func assign() -> [String]{
let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("words", ofType: "txt")
let content = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)//xcode marked that line with green
let newArray = content!.componentsSeparatedByString("\n")
return newArray
}
class ViewController: UIViewController, UITextFieldDelegate {
let newArray: [String] = assign()
@IBOutlet weak var textBox: UITextView!
@IBOutlet weak var firstInput: UITextField!
@IBOutlet weak var resultLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
firstInput.returnKeyType = .Search
firstInput.delegate = self
textBox.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getFromPath() {
//getFromPath() func used to be in assign func.
var letters = firstInput.text
var res = search(set: newArray, letters: letters)
textBox.text! = ""
for element in res {
textBox.text = (textBox.text ?? "") + "\n" + "\(element)"
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if firstInput.text == "" {
}
else {
getFromPath()
}
self.view.endEditing(true)
return false
}
func search(#set: [String], letters: String) -> [String] {
let result = filter(set) { item in
for char in letters {
if !contains(item, char) {
return false
}
}
return true
}
return result
}
}
答案 0 :(得分:2)
好像你的捆绑包中没有该文件。
确保文件已添加到目标,请检查检查器。
在
中包装关键初始化if let someObject = source as? someType
{
}
答案 1 :(得分:1)
将文件拖到项目中,并将其与项目文件放在一起。如果需要,请务必选择复制项目:
class ViewController: UIViewController {
let wordsUrl = NSBundle.mainBundle().URLForResource("words", withExtension: "txt")!
override func viewDidLoad() {
super.viewDidLoad()
var error: NSError?
if wordsUrl.checkResourceIsReachableAndReturnError(&error) {
println(true)
if let myString = String(contentsOfURL: wordsUrl, encoding: NSUTF8StringEncoding, error: &error) {
let myArray = myString.componentsSeparatedByString("\n")
println(myArray)
} else if let error = error {
println(error.description)
}
} else if let error = error {
println(error.description)
}
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}