Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Build a Vending Machine App in Swift 2.0 Loading Data From a Resource Type Methods

Ethan Neff
Ethan Neff
27,058 Points

class func blah() {} or static func blah() {}

Basically classes can take either 'class' or 'static' for Type Methods (example below).

Is there any benefit from using 'class' over 'static'? Or can I just use 'static' for everything (both my classes and structs)?

class ClassExample {
  class func TypeMethodClass() {
    print("class class")
  }
  static func TypeMethodStatic() {
    print("class static")
  }
}

struct StructExample {
  static func TypeMethodStatic() {
    print("struct static")
  }
}

ClassExample.TypeMethodClass()
ClassExample.TypeMethodStatic()
StructExample.TypeMethodStatic()
Greg Kaleka
Greg Kaleka
39,021 Points

Completely unrelated to your question, and I'm sure you know this, but just in case - it's best practice to name your functions (static, class or otherwise) with lowercase first letters.

class ClassExample {
  class func typeMethodClass() {
    print("class class")
  }
  static func typeMethodStatic() {
    print("class static")
  }
}

1 Answer

Ethan Neff
Ethan Neff
27,058 Points

found the answer:

static and class both associate a method with a class, rather than an instance of a class. The difference is that subclasses can override class methods; they cannot override static methods.