Skip to content

Instantly share code, notes, and snippets.

@silentsudo
Last active December 2, 2016 21:10
Show Gist options
  • Save silentsudo/cd1bb3330aeaac8262a4527ff8117749 to your computer and use it in GitHub Desktop.
Save silentsudo/cd1bb3330aeaac8262a4527ff8117749 to your computer and use it in GitHub Desktop.
inheritance in swift
//: Playground - noun: a place where people can play
import UIKit
enum ServerError: Error {
case SERVER_NOT_INITIALIZED(String)
}
class Server {
var name: String? = nil;
var started:Bool = false
init(name:String, started: Bool) {
self.name = name
self.started = started
}
func start() {
started = true;
}
func server(fileName: String) throws -> String? {
if(started) {
return "Serving using generic method: \(fileName)"
} else {
return nil
}
}
func stop() {
started = false;
}
}
class MediaServer: Server {
override init(name: String, started: Bool) {
super.init(name:name, started:started)
}
//Can add check here if fileName ends with .mp4/.avi/.flv or .mp3/.wav
override func server(fileName: String) throws -> String? {
if(started) {
return "Serving Media: \(fileName)"
} else {
throw ServerError.SERVER_NOT_INITIALIZED("Server not initialized")
}
}
}
//Generic server response
var server: Server = Server(name: "Generic Server", started: false)
//let response = server.server(fileName: "a.txt")
do {
let response = try server.server(fileName: "a.txt")
print("Response from \(server.name!) is \(response)")
} catch is ServerError {
print("Exception is called: server error")
}
//Media Server response
//Generic server response
var mediaServer: Server = MediaServer(name: "Media Server", started: false)
mediaServer.start()
//let response = server.server(fileName: "a.txt")
do {
let response = try mediaServer.server(fileName: "a.mp4")
print("Response from \(mediaServer.name!) is \(response!)")
} catch {
print("Exception is called: server error: \(error)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment