在我的代码中,我收到以下错误:
// cannot convert value of type 'NSURL' to expected argument type 'String'
和
// Extra argument 'error' in call
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 :(得分:0)
您正在创建路径作为NSURL(这是URLByAppendingPathComponent
返回的内容),但fileExistsAtPath
将路径的字符串表示形式作为参数。 TheNSURL的path
财产会给你这个......
if !fileManager.fileExistsAtPath(path.path!)
关于copyItemAtPath
,您可能正在查看Objective-C签名而不是Swift签名。对于斯威夫特来说:
func copyItemAtPath(_ srcPath: String,
toPath dstPath: String) throws
因此,您可以使用do/try
来捕获它可能抛出的异常。
答案 1 :(得分:0)
如错误告诉您,您需要使用fileManager.fileExistsAtPath:
而不是String
来致电NSURL
。
此外,Swift不使用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 {
}
}
}
}