In my application I want to create an generic method which creates an array of object depening on the given type T.
I created the following function:
fun
Working version of the code in the question ( second part )
• Init is required because a function returns a generic person Type (
newPerson(as person:T) -> T
)
• I've replaced the class methods func getWorkingHours()
by var workingHours { get }
.. It works equally, in a more 'swifty' way.
• getWorkingHours()
returns hours, as the name indicates, not a Person..
class Person {
required init() {}
var workingHours: Float { get { return 40 } }
}
class Boss : Person {
override var workingHours: Float { get { return 100 } }
}
class Worker : Person {
override var workingHours: Float { get { return 42 } }
}
func getWorkingHours(_ person: T) -> Float {
return person.workingHours
}
func newPerson(as person: T) -> T {
return T()
}
// -----------------------------------------------
let worker = Worker()
let boss = Boss()
print( getWorkingHours(worker) ) // prints 42.0
print( getWorkingHours(boss) ) // prints 100.0
let person = newPersonOfSameClass(as: worker)
print( getWorkingHours(person) ) // prints 42.0
Hope it helps.. This code is ready for copy/paste in playground.