I'm trying to figure out the best pattern to work with objects in Swift.
i think i got it right with the initializers, both convenience and default... but what happen with the class factory methods?
I tried to create a simple class Person and a subclass Student, with few properties and methods. is it the most correct way to do it?
class Person{
var _name: String
var _surname: String
var _dateOfBirthday: String
var _phoneNumb: [String]
init(name:String, surname:String, dateOfBirthday:String, phone:[String]){
self._name = name
self._surname = surname
self._dateOfBirthday = dateOfBirthday
self._phoneNumb = phone
}
convenience init() {
self.init(name:"",surname:"",dateOfBirthday:"", phone:[])
}
convenience init(name:String){
self.init(name:name,surname:"",dateOfBirthday:"", phone:[])
}
}
class Student:Person{
var _studentId:Int
init(name: String, surname: String, dateOfBirthday: String, phone: [String], id:Int) {
self._studentId = id
super.init(name: "", surname: "", dateOfBirthday: "", phone: [])
}
convenience init(){
self.init(name: "", surname: "", dateOfBirthday: "", phone: [], id:0)
}
convenience init(name:String){
self.init(name:name,surname:"",dateOfBirthday:"", phone:[], id:0)
}
}
what if i want to add a class factory method? would it be something like this or i'm doing it wrong?
class func Person() -> Person {
var x = Person()
x._telephoneNumber = [String]() // is this needed? or i can initialize it later?
return x
}
class func PersonWithName(name:String) -> Person {
var x = Person(name:name, surname:"", dateOfBirthday:"", telephoneNumber:[])
return x
}
is this correct? why would it be better to use the init instead of the class factory?