Init
When we create a struct
and add some properties to it, we automatically have access to its constructor or init
. However, we can define that init
ourselfs, defining also what parameters will be necessary.
struct Person {
var fullName: String
init(name: String, lastName: String) {
fullName = "\(name) \(lastName)"
}
}
This will invalidate the default init
, but we can add as many as we need.
struct Person {
var fullName: String
init(fullName: String) {
self.fullName = fullName
}
init(name: String, lastName: String) {
fullName = "\(name) \(lastName)"
}
}
Person(fullName: "Pablo Guardiola")
Person(name: "Pablo", lastName: "Guardiola")
Functions
We can add functions to our objects and call them as we do with properties. From these functions we can access to the properties:
struct Person {
var fullName: String
func getWelcomeMessage() -> String {
"Welcome \(fullName)"
}
}
var myUser = Person(fullName: "Pablo Guardiola")
myUser.getWelcomeMessage()
Be the first to comment