![](/img/trans.png)
[英]Swift - Cannot invoke initializer for type 'NSDictionary'
[英]Swift2: Cannot invoke initializer for type '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本機類型String。 你還需要實現Swift 2.0做try catch錯誤處理。 試試這樣:
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!
將阻止錯誤傳播(盡管如果發生錯誤,您將收到運行時錯誤)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.