Swift 2.0 for programmers Part#3


Class

class Person {
    var firstName : String = ""
    var lastName : String = ""
    var age : Int = 0
    
    // default initializer 
    init() {}
    
    init(firstName: String, lastName: String, age: Int) {
        self.firstName = firstName
        self.lastName = lastName
        self.age = age
    }
    
    deinit {
        // clean up code
    }
    
    // toString method
    func description() -> String {
        return "Person firstName: \(firstName) lastName: \(lastName) age: \(age)"
    }
}

var john = Person()
john.firstName = "John"
john.description()

john = Person(firstName: "John", lastName: "Doe", age: 35)

Inheritance

class Person {
    var firstName : String = ""
    var lastName : String = ""
    var age : Int = 0

    
    // default initializer 
    init() {}
    
    init(firstName: String, lastName: String, age: Int) {
        self.firstName = firstName
        self.lastName = lastName
        self.age = age
    }
    
    deinit {
        // clean up code
    }
    
    // toString method
    func description() -> String {
        return "Person firstName: \(firstName) lastName: \(lastName) age: \(age)"
    }
    
    // Child classes will not be able to override this method
    final func finalMethod() {
        
    }
}

class SpecialPerson : Person {
    
    var specialVariable : String
    
    func getAge() -> Int {
        return age - 5
    }
    
    override init() {
        specialVariable = ""
        super.init()
    }
    
    override func description() -> String {
        let parentDescription = super.description()
        return "\(parentDescription) and speicalVariable: \(specialVariable)"
    }
    
}

Computer property

class Person {
    var firstName : String = ""
    var lastName : String = ""
    var age : Int = 0

    
    // default initializer 
    init() {}
    
    init(firstName: String, lastName: String, age: Int) {
        self.firstName = firstName
        self.lastName = lastName
        self.age = age
    }
    
    deinit {
        // clean up code
    }
    
    // toString method
    func description() -> String {
        return "Person firstName: \(firstName) lastName: \(lastName) age: \(age)"
    }
    
    // Child classes will not be able to override this method
    final func finalMethod() {
        
    }
    
    // computer property
    var name : String {
        get {
            // if only get is defined, then it is a read-only property
            return firstName + " " + lastName
        }
        set {
            // split "newValue into two pieces 
            var splits = newValue.componentsSeparatedByString(" ")
            firstName = splits [0]
            lastName = splits [1]
        }
    }
    
    var fullName : String {
        return name
    }
}

Class level/Type level/Static members

class Person {
    var firstName : String = ""
    var lastName : String = ""
    var age : Int = 0
    static var commonProperty : String = "Hello"
    static var commonReadOnlyProperty : String {
        return "World"
    }
    
    // default initializer 
    init() {}
    
    init(firstName: String, lastName: String, age: Int) {
        self.firstName = firstName
        self.lastName = lastName
        self.age = age
    }
    
    // toString method
    func description() -> String {
        return "Person firstName: \(firstName) lastName: \(lastName) age: \(age)"
    }
    
    static func staticMethod() {
        print("This is a static method")
        
        // As this is a static method, you can not access any instance level variable/method
        //age++       // compile error
        
        print("common property: \(commonProperty)")
    }
}

Person.commonProperty                               // "Hello"
Person.commonReadOnlyProperty                       // "World"
Person.commonProperty = "New Value"
// Person.commonReadOnlyProperty = "Another value" // compile error, Read only property
Person.commonProperty                               // "New Value"
Person.staticMethod()

Lazy property


class Person {
    var firstName : String = ""
    var lastName : String = ""
    var age : Int = 0
    lazy var networkData : String = {
        return self.loadDataFromNetwork()
    }()
    
    // default initializer 
    init() {}
    
    init(firstName: String, lastName: String, age: Int) {
        self.firstName = firstName
        self.lastName = lastName
        self.age = age
    }
    
    // toString method
    func description() -> String {
        return "Person firstName: \(firstName) lastName: \(lastName) age: \(age)"
    }
    
    func loadDataFromNetwork() -> String {
        print("Loading data from network...")
        // Time consuming network call goes here
        return "Hello"
    }
}

Points to be noted

  • lazy can not be constant variable, i.e can not started with let
  • lazy property won’t get initialized until the variable gets called

Observers

class Person {
    var firstName : String = "" {
        willSet {
            // will get called just before the value change
            print("New value will be: \(newValue)")
        } didSet {
            // will get called just after the value change
            print("Old value was: \(oldValue)")
        }
    }
    var lastName : String = ""
    var age : Int = 0
    
    // default initializer 
    init() {}
    
    init(firstName: String, lastName: String, age: Int) {
        self.firstName = firstName
        self.lastName = lastName
        self.age = age
    }
    
    // toString method
    func description() -> String {
        return "Person firstName: \(firstName) lastName: \(lastName) age: \(age)"
    }
}

Access Modifies

public class Person {
    var firstName : String = "" {
        willSet {
            // will get called just before the value change
            print("New value will be: \(newValue)")
        } didSet {
            // will get called just after the value change
            print("Old value was: \(oldValue)")
        }
    }
    var lastName : String = ""
    private var age : Int = 0
    
    // default initializer 
    init() {}
    
    init(firstName: String, lastName: String, age: Int) {
        self.firstName = firstName
        self.lastName = lastName
        self.age = age
    }
    
    // toString method
    internal func description() -> String {
        return "Person firstName: \(firstName) lastName: \(lastName) age: \(age)"
    }
}

Points to be noted

  • There are 3 access modifiers: private, internal, public
  • private: Accessible from the same source file
  • internal: Default access level, Accessible from same module
  • public: Accessible for all
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s