Learn Swift by Examples: #3


Class

import UIKit

class User {
    var name : String = ""
    var pass : String = ""
    var age : Int = 0
    var firstName : String
    var lastName : String
    var fullName : String {
        return firstName + " " + lastName
    }
    
    static var userCount: Int = 0
    
    init() {
        name = "admin"
        pass = "admin"
        age = 18
        firstName = ""
        lastName = ""
    }
    
    convenience init(name: String) {
        self.init()
        self.name = name
    }
    
    func toString() -> String {
        return ("Name: \(name) pass: \(pass) age: \(age)")
    }
    
    deinit {
        // de-initialize code goes here
    }
}

var anUser = User()

anUser.name = "Don"
anUser.pass = "123"
anUser.age = 10
anUser.toString()

var anotherUser = User(name: "King")

class NormalUser : User {
    
    var level : Int
    lazy var salary = getSalary()
    var observerProperty : String = "Admin" {
        willSet {
            println("About to change to \(newValue)")
        }
        didSet {
            println("Have changed from \(oldValue)")
        }
    }
    
    override init() {
        level = 3
        super.init()
    }
    
    func getLevel() -> Int {
        return level;
    }
    
    override func toString() -> String {
        let originalToString = super.toString()
        return ("\(originalToString) level: \(level)")
    }
}

func getSalary() -> Int {
    println("Long running task...")
    return random()
}

User.userCount = 1

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