1

Part 3 of the taste of Swift explores class objects in Apple's Swift language. A class allows you to group methods (class functions) together that belong together. Class Person groups some information of people working in an office. Class Pay inherits class Person and adds pay information. Class File groups file read and write methods. By convention class names start with a capital letter. Once a class is written it can be inherited by another class which eliminates a lot of extra code writing. Part 4 will talk about a related object, the structure. Swift has elevated the structure to be almost a class.

At least Swift isn't one of those languages that forces you to start with a class no matter what. A class is a nice coding tool, and that's all.

Swift uses three access levels:
public (can be imported by other modules/frameworks)
internal (default, no import by other modules/frameworks))
private (access only within the defining source code)
If no access level is used, Swift defaults to internal.

Coming in the fall of 2015 ...
Swift2 replaces println() with just print() that has a newline default. There are some other syntax changes and a much improved error handling.
The good news is, there will be a Swift 1-to-2 migrator utility to change Swift1 syntax to Swift2 syntax.

Edited by vegaseat: class func added

//
//  main.swift
//  Taste_of_swift3
//
// exploring Apple's Swift language, part 3
// vegaseat   23jun2015    used Swift version 1.2

import Foundation

// class ...

// you can group functions that belong together in a class
// functions inside a class are called methods
class Animal {
    var name: String
    var sound: String
    // initializer is required
    init(name: String, sound: String) {
        self.name = name
        self.sound = sound
    }
    
    // a method of class Animal
    func speak() {
        println("\(self.name) goes '\(self.sound)'")
    }
    
    // this method returns a string argument
    func mood() -> String {
        return "\(self.name) looks happy today!"
    }
    
    // this method accepts an argument
    func hungry(yesno: String) {
        if yesno == "yes" {
            println("\(self.sound) \(self.sound) means \(self.name) is very hungry!")
        } else {
            println("Silence means not hungry!")
        }
    }
    
}

// create instance roger of class Dog
let roger = Animal(name: "Roger", sound: "woof")
// call some instance methods
roger.speak()           // Roger goes 'woof'
// this method returns an argument
println(roger.mood())   // Roger looks happy today!

// create an instance for a cat named Mitten
let mitten = Animal(name: "Mitten", sound: "meeow")
mitten.speak()           // Mitten goes 'meeow'
// this method takes an argument like "yes" or "no"
mitten.hungry("yes")     // meeow meeow means Mitten is very hungry!
mitten.hungry("no")      // Silence means not hungry!

println("---------------------")

class Person {
    var name: String
    var age: Int
    
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
    
    func intro() {
        println("Hello, I am \(self.name)!")
    }
    
    func detail() {
        if self.age < 0 {
            println("\(self.name)'s age is private!")
        } else {
            println("\(self.name) is \(self.age) years old.")
        }
    }
    
    func income() {
        println("My income is private information!")
    }
    
    func officeTalk() {
        // random office talk
        // generate a random integer beween 0 and 3
        var randInt = Int(arc4random_uniform(4))
        switch randInt {
        case 0: println("They don't pay enough!")
        case 1: println("Lousy coffee today!")
        case 2: println("It's cold here!")
        case 3: println("Look at that rear!")
        default: println("Bill's birthday today!")  // just in case
        }
    }
}

// create an immutable instance with let
let bob = Person(name: "Bob", age: 35)

bob.intro()  // Hello, I am Bob!
bob.detail() // Bob is 35 years old.

// you can change Bob's age, but not the instance
bob.age = 45

bob.detail()  // Bob is 45 years old.

// an age of less than zero makes age private info
let susan = Person(name: "Susan", age: -1)

susan.detail()      // Susan's age is private!
susan.income()      // My income is private information!
// office talk heard at random
susan.officeTalk()  // eg. "It's cold here!"

// class Pay inherits class Person
class Pay: Person {
    var pay: Float
    
    init(name: String, age: Int, pay: Float) {
        self.pay = pay
        // self.name and self.age shared with class Person
        super.init(name: name, age: age)
    }
    
    // age not required, will default to -1
    convenience init(name: String, pay: Float) {
        self.init(name: name, age: -1, pay: pay)
    }
    
    override func income() {
        println("\(name) gets $\(self.pay) a month pay")
    }
    
    // this method does not need init() data or class instance
    // call with Pay.bossTalk()
    class func bossTalk() {
        println("Management: Work hard and get more pay!")
    }
}

//let jim = Person(name: "Jim", age: 32)
let jimPay = Pay(name: "Jim", age: 32, pay: 4231.25)

// uses inherited intro()
jimPay.intro()   // Hello, I am Jim!
jimPay.detail()  // Jim is 32 years old.

// income() message is different, applied override
jimPay.income()  // Jim gets $4231.25 a month pay

// leave the age off, will use convenience init() with age default value
let tomPay = Pay(name: "Tom", pay: 3781.57)

tomPay.intro()       // Hello, I am Tom!
tomPay.detail()      // Tom's age is private!
tomPay.income()      // Tom gets $3781.57 a month pay
tomPay.officeTalk()  // eg. "They don't pay enough!"

// a method that doesn't use init() data
Pay.bossTalk()  // Management: Work hard and get more pay!

println("---------------------")

// writing/reading a text file using a class ...
class File {
    // "class func" allows use of File.read(path) method call
    // an initiallizer is not required
    // utf8 is default encoding
    class func read(path: String, utf8: NSStringEncoding =
        NSUTF8StringEncoding) -> String? {
            var error: NSError?
            // use ternary expression "? :"
            // if file exists return content else return nil
            return NSFileManager().fileExistsAtPath(path) ?
                String(contentsOfFile: path, encoding: utf8, error: &error)! :
            nil
    }
    // "class func" allows use of File.write(path, text) method call
    class func write(path: String, _ content: String, utf8: NSStringEncoding = NSUTF8StringEncoding) -> Bool {
        var error: NSError?
        // returns true on success
        return content.writeToFile(path, atomically: true, encoding: utf8, error: &error)
    }
}

// create text, file name and full file path
let mytext = "good morning everyone!"

let fname = "aatest.txt"

// full path (directory/fname)
let mypath = "\(NSHomeDirectory())/Documents/\(fname)"

// for testing ...
println(NSHomeDirectory())
println(mypath)

// try to write the file
if File.write(mypath, mytext) {
    println("file written")             // file written
} else {
    println("error writing file")
}

// try to read the file
if let mytext2 = File.read(mypath) {
    println(mytext2)                     // good morning everyone!
} else {
    println("error reading file")
}

// extra ...
if NSFileManager().fileExistsAtPath(mypath) {
    println("file \(mypath) exists!")
}
2
Contributors
5
Replies
37
Views
2 Years
Discussion Span
Last Post by ddanbe
0

Note that the NS prefix comes in from Objective C.

Also note that most Swift objects are by value, but class instances are by reference.

Edited by vegaseat

1

When Steve Jobs left Apple (for a while) in 1985, he started a new compagny NeXT.
They developed a new OS called NeXTStep. Hence NS. This OS was mostly written in Objective C.

1

Class objects become important when you start working with GUI applications using the UIKit (iOS) or Cocoa (OS X) frameworks.

A real informative video on building apps for iOS (iPhone and iPad) with the Xcode IDE is at (first in a series of lectures) ...
https://www.youtube.com/watch?v=GOEPVM5OzJk

You will learn a lot more about Swift by doing a project like the one in the video.

Edited by vegaseat

Votes + Comments
Great video tip!
0

Just watched the second video lecture. Swift and the IDE that goes with it are really awesome. Think I'm gonna buy me a Mac again. Don't think Apple is eager to bring this out on Windows ...

Edited by ddanbe: addition

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.