how to create a struct in swift

To create a struct in Swift, follow these steps:

  1. Decide on the properties you want your struct to have. These can be any of Swift's built-in data types, as well as other structs or classes that you have defined.

  2. Define the struct by using the struct keyword, followed by the name of your struct. Then, inside curly braces, list the properties you want your struct to have.

main.swift
struct Person {
    var name: String
    var age: Int
}
56 chars
5 lines
  1. You can now create instances of your struct by providing values for its properties. To do this, use the name of the struct followed by parentheses, and inside the parentheses, provide the values for each of the struct's properties.
main.swift
let john = Person(name: "John Doe", age: 30)
print(john.name) // Output: John Doe
print(john.age) // Output: 30
112 chars
4 lines
  1. Structs also support methods, which are functions that operate on the struct's properties. To define a method, add a function inside the struct definition, like this:
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
  1. You can call this method on instances of your struct just like you would call any other method:
main.swift
let john = Person(name: "John Doe", age: 30)
john.sayHello() // Output: Hello, my name is John Doe and I'm 30 years old.
121 chars
3 lines

gistlibby LogSnag