2015-09-27 19 views
1

我刚刚安装了新的Swift 2的Xcode 7,现在有50多个错误说“stringByAppendingPathComponent”不可用,而我应该使用“URLByAppendingPathComponent”。我已经设定我所有的纹理特性的,像这样:在Swift 2中使用什么来代替stringByAppendingPathComponent

let dropTexture = SKTexture(image: UIImage(
    contentsOfFile:NSBundle.mainBundle().resourcePath!.stringByAppendingPathComponent(
     "P04_rainDrop1.png"))!) 

我一直在做这所以当SKScene改变他们没有在记忆里,它已经完美的工作。但是直接替换“URLByAppendingPathComponent”不会修复错误。

我该如何改变这种情况来修复错误并获得相同的SKTexture?通过添加扩展到字符串

let dropTexture = SKTexture(image: UIImage(
     contentsOfFile:(NSBundle.mainBundle().resourcePath! as NSString).stringByAppendingPathComponent(
      "P04_rainDrop1.png"))!) 

利奥Dabus说得好,你可以保存自己的所有铸造:

回答

4

所有你需要做的是转换为NSString的恢复stringByAppendingPathComponent,像这样。但是,您不应该像他所建议的那样调用NSString(string:),这会生成额外的字符串。只是演员:

extension String { 
    func stringByAppendingPathComponent(pathComponent: String) -> String { 
     return (self as NSString).stringByAppendingPathComponent(pathComponent) 
    } 
} 
+0

这仍然是一个体面的方式来实现这一目标吗?我找不到是苹果在Swift上实现了这一点但尚未 – 2017-02-27 08:51:29

+0

永远不要将字符串转换为NSString。查看Apple规定的内容。 https://github.com/apple/swift/blob/adc54c8a4d13fbebfeb68244bac401ef2528d6d0/stdlib/public/SDK/Foundation/NSStringAPI.swift#L1345 – Brennan

+0

@Brennan不够公平。如果不一定,我只是不喜欢回答“不这样做”。但我确实在任何可能的地方使用URL而不是字符串filepath(现在几乎无处不在)。 – matt

相关问题