Null Object Pattern in Swift

January 18, 2016 · View on GitHub

// // ViewController.swift // NullObject // // Created by Suprie on 1/18/16. // Copyright © 2016 Suprie. All rights reserved. //

import UIKit

protocol StationProtocol { var id: Int { set get } var name: String { set get } var isEmpty: Bool { set get } }

class EmptyStation : StationProtocol { var id = -1 var name = "" var isEmpty = true }

class Station : StationProtocol { var id = 0 var name = "" var isEmpty = false

init(id: Int, name: String){
    self.id = id
    self.name = name
}

}

class Video { static let nullVideo: NullVideo = NullVideo()

var id: Int
var title: String

init(id: Int, title: String) {
    self.id = id
    self.title = title
}

}

class NullVideo: Video {

convenience init() {
    self.init(id: -1, title: "")
}

}

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func NotNillTapped(sender: AnyObject) {
    let station = Station(id: 1, name: "Tanah abang")
    processStation(station)
}

@IBAction func NilTapped(sender: AnyObject) {
    let emptyStation = EmptyStation()
    processStation(emptyStation)
}

@IBAction func vidioNotNilTapped(sender: AnyObject) {
    let video = Video(id: 1, title: "Haloha")
    processVideo(video)
}

@IBAction func vidioNilTapped(sender: AnyObject) {
    processVideo(Video.nullVideo)
}

func processStation(station: Station) {
    let alert = UIAlertController(title: "Yay", message: "Object is not null", preferredStyle: .Alert)
    alert.addAction(UIAlertAction(title: "Ummm, Okay", style: .Default, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)
}

func processStation(station: EmptyStation) {
    let alert = UIAlertController(title: ":(", message: "Object is null", preferredStyle: .Alert)
    alert.addAction(UIAlertAction(title: "Ummm, Okay", style: .Default, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)
}


func processVideo(video: Video) {
    let alert = UIAlertController(title: "Yay", message: "Object is not null", preferredStyle: .Alert)
    alert.addAction(UIAlertAction(title: "Ummm, Okay", style: .Default, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)
}

func processVideo(video: NullVideo) {
    let alert = UIAlertController(title: ":(", message: "Object is  null", preferredStyle: .Alert)
    alert.addAction(UIAlertAction(title: "Ummm, Okay", style: .Default, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)
}

}