// Times.swift Copyright (c) Kari Laitinen // http://www.naturalprogramming.com // 2014-10-10 File created. // 2016-11-09 Last modification. // This program demonstrates: // - inheritance and overriding of methods // - how to get the current system time import Foundation // Swift does not have abstract classes, i.e., classes that would // have methods without implementation. The following class is // a kind of imitation of an abstract class, as it should be used // only as a superclass for other classes. class CurrentTime { var current_hours : Int = 0 var current_minutes : Int = 0 var current_seconds : Int = 0 init() { // This initializer reads the current computer time let current_date = Date() let calendar = Calendar.current current_hours = calendar.component( Calendar.Component.hour, from: current_date ) current_minutes = calendar.component( Calendar.Component.minute, from: current_date ) current_seconds = calendar.component( Calendar.Component.second, from: current_date ) } func print_time() { print( "\n Objects of class CurrentTime should not be created.\n") } } // It is not entirely true that the 12-hour a.m./p.m. time // would be used everywhere in America, and the 24-hour time // would be used everywhere in Europe. The names AmericanTime // and EuropeanTime just happen to be nice names to // distinguish these two different ways to display time. class AmericanTime : CurrentTime { override func print_time() { let american_hours = [ 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ] print( String( format: "%d:%02d:%02d", american_hours[ current_hours ], current_minutes, current_seconds ), terminator: "" ) if current_hours < 12 { print( " a.m." ) } else { print( " p.m." ) } } } class EuropeanTime : CurrentTime { override func print_time() { print( String( format: "%d:%02d:%02d", current_hours, current_minutes, current_seconds ) ) } } // Here begins the main program. // time_to_show will refer either to an EuropeanTime object or to // an AmericanTime object, depending on what the user wants to see. var time_to_show : CurrentTime print( "\n Type 12 to see the time in 12-hour a.m./p.m format." + "\n Any other number gives the 24-hour format. ", terminator: "" ) let user_response = Int( readLine()! )! if user_response == 12 { time_to_show = AmericanTime() } else { time_to_show = EuropeanTime() } print( "\n The time is now ", terminator: "" ) time_to_show.print_time() print( "\n" )