1

I want to use NSArray's arrayWithContentsOfFile method in Swift since I have to create an Swift Array from the contents of a file, but how can I call it from within Swift code?

Since arrayWithContentsOfFile: is a class method implemented in Objective-C's built-in NSArray type, I cannot call it as called in this post, which calls an instance method by type-casting the Swift's Array to Objective-C's NSArray.

So is there any way to call the method, or any equivalent method like that?

Community
  • 1
  • 1
Blaszard
  • 30,954
  • 51
  • 153
  • 233

1 Answers1

8

The method can be called in Swift like so: NSArray(contentsOfFile: "PATH")

Using the method like so: NSArray.arrayWithContentsOfFile("PATH") is deprecated.

This is a constructor, and should be used in the following manner:

var array = NSArray(contentsOfFile: "PATH")
Jacob
  • 2,769
  • 3
  • 21
  • 29
  • Technically, there are two different methods called here. `NSArray(contentsOfFile: "PATH")` calls `-initWithContentsOfFile:` in Objective-C, whereas `NSArray.arrayWithContentsOfFile("PATH")` (note: not `withContentsOfFile`) calls `+arrayWithContentsOfFile:`. It is true that the initializer is preferred over the class method when an initializer is available. – newacct Jun 17 '14 at 19:01
  • @newacct Yes; however, `NSArray.arrayWithContentsOfFile("PATH")` is deprecated and therefore should not be used, as I stated in my answer. – Jacob Jun 18 '14 at 14:04
  • 2
    It's not just deprecated, it's unavailable in Swift. The compiler maps the ObjC initializer to a Swift initializer, then disables the ObjC convenience constructor because it's known to just call through to the similarly named initializer. – rickster Jun 18 '14 at 14:28