Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Arda KARACA
1,793 PointsWhat is init method?
Where am I need to use init method?
3 Answers
Steve Hunter
57,712 PointsHi Arda,
The init method can be part of a class or struct. This method is called every time a new instance of the class or struct is created.
So, within the init method you can do all the setup work for your class such as initialising variables.
I hope that helps you. If not, please just ask and I'll try to be clearer!
Cheers,
Steve.
Arda KARACA
1,793 PointsThanks Steve. I want to ask something with some code.
import UIKit
enum Status {
case Arrived, Waiting, Sent, NotAvaliable
init(){
self = .NotAvaliable
}
}
enum Type {
case Fragile, ColdPackage, QuickDelivery, NormalPackage
init(){
self = .NormalPackage
}
}
struct cargoStatus {
var property = Type()
var status = Status()
var description: String
var recipient: String
}
var television = cargoStatus(property: .QuickDelivery, status: .Sent, description: "LCD TV", recipient: "Somebody")
I want to make it like, if I enter Status and Property it's going to use it, if I didn't enter some Status and Property it's going to use default value. How can I do it?
Thanks Arda
Steve Hunter
57,712 PointsHave a look through the swift courses for default & convenience initialisers. Those allow you to handle various levels of detail in terms of the parameters you pass in.
In essence, you declare various initialisers in, nearly, the same way with different numbers of parameters.
You set the undeclared ones within your method where it is not supplied in the code.
Google is likely to more informative than I am, to be honest.
Steve.