Swift For Dummies
Book image
Explore Book Buy On Amazon

Classes are the heart of any object-oriented programming language. Unlike classes in Objective-C and some other languages, Swift’s classes need no header declaration. Instead, you get the entire class (or structure or enumeration) definition in a format like this:

class MyClass {
 var storedNumber: Int = 0
 init (myNumber storedNumber: Int) {
 self.storedNumber = storedNumber
 }
 func simpleDescription() -> String {
  return String(self.storedNumber)
 }
}
var test = MyClass(myNumber: 15)
println ("myNumber is " + test.simpleDescription());

The code in this example defines a class. Note the following characteristics:

  • It declares a stored property. It is an Int set initially to 0.

  • It creates an initializer that takes an Int as a parameter. The external name is myNumber and the internal name is storedNumber. The initializer sets the class instance value self.storedNumber using the storedNumber parameter (with the external name myNumber).

  • It declares a function called simpleDescription that returns a String representation of the stored number.

About This Article

This article is from the book:

About the book author:

Jesse Feiler is a developer, web designer, trainer, and author. He has worked with mobile devices starting with Apple’s Newton and continuing with the Apple’s iOS and OS X products, including the iPhone and iPad. He is heard regularly on WAMC Public Radio’s The Roundtable.

This article can be found in the category: