2

I'm trying to implement the following code in an playground:

class File {
    class func open(path: String, encoding: NSStringEncoding = NSUTF8StringEncoding) -> String? {
        if NSFileManager().fileExistsAtPath(path) {
            do {
                return try String(contentsOfFile: path, encoding: encoding)
            } catch let error as NSError {
                print(error.code)
                return nil
            }
        }
        return  nil
}

But when I try to access the class:

let read = File()
let content = read.open("ba")

I get this error: "Instance member "read" cannot be used on type custom type "File" "

Any of you knows why of this error or how can I fix it?

I would really appreciate your help.

user2924482
  • 8,380
  • 23
  • 89
  • 173

1 Answers1

2

You've defined a static method so its accessible like

let content = File.open("ba")
SirH
  • 535
  • 2
  • 7
  • What is the difference between static method and non- static method? – user2924482 May 10 '16 at 21:54
  • Methods and variables that are not declared as static are known as instance methods and instance variables. To refer to instance methods and variables, you must instantiate the class first means you should create an object of that class first.For static you don't need to instantiate the class u can access the methods and variables with the class name using period sign which is in (.) – SirH May 10 '16 at 21:57
  • Why should use over the other? – user2924482 May 11 '16 at 17:11