Swift2:不能调用types为'NSString'的初始值设定项
我是Swift开发新手。 我只是将现有的工作代码转换为swift2,同时从6更新Xcode 7。
var err: NSError? let template = NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: &err) as! String let iframe = template.stringByReplacingOccurrencesOfString("{{VIDEO_ID}}", withString: id, options: NSStringCompareOptions.allZeros, range: nil) if err != nil { return false }
然后,我得到这个错误消息:
Cannot invoke initializer for type 'NSString' with an argument list of type '(contentsOfFile: String, encoding: UInt, error: inout NSError?)'
你有什么主意吗? 非常感谢!
你应该使用Swift本地types的string。 你也需要实现Swift 2.0做try catcherror handling。 尝试像这样:
let template = try! String(contentsOfFile: path!, encoding: NSUTF8StringEncoding) let iframe = template.stringByReplacingOccurrencesOfString("{{VIDEO_ID}}", withString: id, options: [], range: nil)
如果你想处理这个错误:
do { let template = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding) let iframe = template.stringByReplacingOccurrencesOfString("{{VIDEO_ID}}", withString: id, options: [], range: nil) } catch let error as NSError { print(error.localizedDescription) }
你应该使用Swift 2的“do-try-catch”语法来处理错误:
do { let template = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding) // Use the template } catch let error as NSError { // Handle the error }
肯定阅读这个文档,因为它显示了一些其他的方式来处理错误 – 例如try?
会在任何错误的情况下给你一个可选的,并try!
将阻止错误传播(尽pipe如果发生错误,您会得到一个运行时错误)。