How to easily reset all structured values with Struct in Swift ?

If you're programming in Swift, it's likely that you're using structured variables with the Struct tool. You may have already wondered how to easily reset all the values of these structured variables without having to manually change each value in your code.

Using a Mutation Function in Struct

One of the most convenient methods is creating a function directly within the structure itself, like this:

struct Recherche {
    var titre: String?
    var age: Int?
    mutating func reset() {
        titre = nil
        age = nil

In this example, we have created a "reset()" function that sets all the variable values to zero.

Now, you can simply execute this function wherever you want to reset the variables in your code, like this:


Categories : Swift

By Guillaume - 02/27/2023 at 05:51 pm

Shar this article :

Similar articles

How to Execute a Function in the Main View from a View Presented Modally with Swift

In some cases, it can be useful to execute a function that resides in the code of the main view of an application from a view presented modally. For example, this might be necessary in a search system where you have a simple search field in the main view and several advanced search fields in the...