9.1.1. Functions (methods) inside structs

We can write functions inside structs. In Swift, they're called methods. For example, we can have a printProfile method in our Profile struct:

struct Person{
    var name:String
    var age:Int
    var city:String
    
//    computed property .....
    var isMinor:Bool{
        if age < 18{
            return true
        }else{
            return false
        }
    }
//    method printProfile...
    
    func printProfile(){
        print(
            """
            Hi! I am \(name).
            I am \(age) years old.
            And I live in \(city)!
            Happy coding!
            """
        )
    }
}

Then we call the method from outside the struct:

It prints:

Struct initializers

We can set the default values for our structs using the initializer method init(). Let's add the init() method in Person where we set the name to "Unknown", age to 18, and city to "Not Given".

Then we can create an instance of Person without providing any parameters, like:

It prints:

So, we can create an instance of a struct with default values by writing init() method. Then we have to set the values later.

Please note: you need to write** init() **method before all the other methods and computed properties.

Source code

Last updated

Was this helpful?