2

I have just installed Xcode 7 with the new Swift 2, and I now have 50+ errors saying that "stringByAppendingPathComponent" is unavailable, and that I should use "URLByAppendingPathComponent" instead. I have been setting all of my texture properties like so:

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

I have been doing this so they do not stay in memory when the SKScene is changed and it has been working perfectly. However directly replacing "URLByAppendingPathComponent" does not fix the errors.

How can I change this to fix the error and get the same SKTexture?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
jwade502
  • 898
  • 1
  • 9
  • 22

1 Answers1

6

All you have to do is cast to NSString to recover stringByAppendingPathComponent, like this:

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

As Leo Dabus rightly says, you can save yourself from all that casting by adding an extension to String. However, you should not, as he suggests, call NSString(string:), which generates an extra string. Just cast:

extension String {
    func stringByAppendingPathComponent(pathComponent: String) -> String {
        return (self as NSString).stringByAppendingPathComponent(pathComponent)
    }
}
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Is that still a decent way to achieve this? I can't find is apple implemented this on Swift nativly yet –  Feb 27 '17 at 08:51
  • Never convert String to NSString. See what is prescribed by Apple. https://github.com/apple/swift/blob/adc54c8a4d13fbebfeb68244bac401ef2528d6d0/stdlib/public/SDK/Foundation/NSStringAPI.swift#L1345 – Brennan Mar 10 '17 at 17:31
  • @Brennan Fair enough. I just don't like to answer "don't do that" if not necessarily. But I do in fact use URL instead of string filepath wherever possible (which now is nearly everywhere). – matt Mar 10 '17 at 18:39