swift2 - Swift: Reducing the length of Init methods -


i reduce length of init method.

struct person {      var id: int     var firstname: string     var lastname: string     var vehicle: string     var location: string     var timezone: string      init (id: int, firstname: string, lastname: string, vehicle: string, location: string, timezone: string ) {         self.firstname = firstname         self.lastname = lastname         self.vehicle = vehicle         self.location = location         self.timezone = timezone     } } 

below instance of person creating. have pass in value of every single variable inline.

let person = person(id: 22, firstname: "john", lastname: "doe", vehicle: "chevy", location: "dallas", timezone: "cst") 

question: how can shrink length of init? in obj-c used create data model class. populate it's variables , pass entire class, reducing length of init method.

i.e.

person *person = [person new]; person.id = 22; person.firstname = "john"; person.lastname = "doe"; person.vehicle = "chevy"; person.location = "dallas"; person.timezone = "cst"  person *person = [person initwithperson:person]; 

what's equivalent way in swift reduce length of init without having initialize every single variable inline? know tuples 1 way, there other best practice?

using struct don't need initializer

struct person {   var id : int?   var firstname: string?   var lastname: string?   var vehicle: string?   var location: string?   var timezone: string? }  var person = person() person.id = 22 person.firstname = "john" person.lastname = "doe" person.vehicle = "chevy" person.location = "dallas" person.timezone = "cst" 

you can same non-optionals

struct person {   var id = 0   var firstname = ""   var lastname = ""   var vehicle = ""   var location = ""   var timezone = "" } 

consider benefit of initializer declare (read-only) constants

struct person {   let id : int   let firstname : string   let lastname : string   let vehicle : string   let location : string   let timezone : string } 

in case have use implicit memberwise initializer.

let person = person(id: 22, firstname: "john", lastname: "doe", vehicle: "chevy", location: "dallas", timezone: "cst") 

Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -