Object Oriented Programming II
Inits and functions.
Object Oriented Programming II
Inits and functions.
0
0
Checkbox to mark video as read
Mark as read

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()

course

Quiz Time!

0 Comments

Join the community to comment
Sign Up
I have an account
Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy