o que são struct? in swift

In Swift, struct is a value type that allows you to define your own data structure. It is similar to a class, but with some important differences.

To define a struct in Swift, you can use the struct keyword followed by the name of the struct. Inside the struct, you can define properties and methods.

Here's an example of how to define a struct in Swift:

main.swift
struct Person {
    var name: String
    var age: Int
    
    func sayHello() {
        print("Hello, my name is \(name) and I'm \(age) years old.")
    }
}
158 chars
9 lines

In the example above, we defined a struct called Person with two properties: name and age. We also defined a method called sayHello() that prints a greeting message with the person's name and age.

To create an instance of a struct, you can simply use the name of the struct followed by parentheses and provide values for the properties:

main.swift
var john = Person(name: "John", age: 30)
41 chars
2 lines

You can access the properties and call the methods of a struct instance using dot notation:

main.swift
print(john.name) // Output: "John"
john.sayHello()  // Output: "Hello, my name is John and I'm 30 years old."
110 chars
3 lines

One important thing to note about structs is that they are value types. This means that when you assign a struct instance to a new variable or pass it as a parameter to a function, a copy of the struct is created.

main.swift
var jane = john
jane.name = "Jane"

print(john.name) // Output: "John"
print(jane.name) // Output: "Jane"
106 chars
6 lines

In the example above, changing the name property of jane does not affect the name property of john, because they are separate instances of the Person struct.

Structs are commonly used in Swift to represent simple data models, such as coordinates, sizes, or person information. They can also be used to encapsulate related data and behavior into a single unit.

related categories

gistlibby LogSnag