2016-02-16 73 views
-1

在我的代码,我得到以下错误: // cannot convert value of type 'NSURL' to expected argument type 'String'// Extra argument 'error' in call无法将类型的价值“NSURL”预期参数类型“字符串”

class ScoreManager { 
var scores:Array<Score> = []; 

init() { 
    // load existing high scores or set up an empty array 
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) 
    let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] 
    let path = documentsURL.URLByAppendingPathComponent("Scores.plist") 
    let fileManager = NSFileManager.defaultManager() 

    // check if file exists 
    if !fileManager.fileExistsAtPath(path) { // cannot convert value of type 'NSURL' to expected argument type 'String' 
     // create an empty file if it doesn't exist 
     if let bundle = NSBundle.mainBundle().pathForResource("DefaultFile", ofType: "plist") { 
      fileManager.copyItemAtPath(bundle, toPath: path, error:nil) // Extra argument 'error' in call 
     } 
    } 
+0

需要实现斯威夫特2不要试图捕捉错误处理 –

+0

BTW命名NSURL'path'是完全误导性的,将它改为'let scoreURL = documentsURL.URLByAppendingPathComponent(“Scores.plist”)',如果你需要路径,只需使用'scoreURL.path!' –

回答

0

您正在创建路径作为NSURL(这是什么URLByAppendingPathComponent返回),但fileExistsAtPath将路径的字符串表示形式作为参数。 TheNSURL的path属性会给你这个...

if !fileManager.fileExistsAtPath(path.path!) 

关于copyItemAtPath,你可能看Objective-C的签名,而不是斯威夫特之一。对于斯威夫特是:

func copyItemAtPath(_ srcPath: String, 
     toPath dstPath: String) throws 

因此你可以使用do/try抓住它可能会抛出异常。

+0

NSURL路径属性返回一个可选字符串 –

+0

好点,我解开它。 – Michael

0

由于错误告诉你,你需要拨打电话fileManager.fileExistsAtPath:String而不是NSURL

此外,斯威夫特不使用error回调,而是使用do/catch

应用,修复程序看起来像这样:

init() { 
    // load existing high scores or set up an empty array 
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString 
    let path = documentsPath.stringByAppendingPathComponent("Scores.plist") 
    let fileManager = NSFileManager.defaultManager() 

    // check if file exists 
    if !fileManager.fileExistsAtPath(path) { 
     // create an empty file if it doesn't exist 
     if let bundle = NSBundle.mainBundle().pathForResource("DefaultFile", ofType: "plist") { 
      do { 
       try fileManager.copyItemAtPath(bundle, toPath: path) 
      } catch { 

      } 
     } 
    } 
} 
相关问题