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, consultant, and author specializing in Apple technologies. He is the creator of Minutes Machine for iPad, the meeting management app, and Saranac River Trail and is heard regularly on WAMC Public Radio for the Northeast’s The Roundtable.

This article can be found in the category: