Swift: Struct Declaration – Learn the Basics in 70 Characters
Swift is a powerful and intuitive programming language for MacOS, iOS, watchOS, and tvOS. It is designed to be easy to use and provide developers with a wide range of tools and features. One of the most important features of Swift is its ability to declare structs, which can be used to create custom data structures. In this article, we’ll look at how to declare a struct in Swift, and what you need to know to get started.
A struct is a data type that allows you to store related pieces of information in one place. Structs are similar to classes, but they are much simpler and more lightweight. To declare a struct in Swift, you use the keyword “struct”, followed by the name of the struct. For example, if you wanted to create a struct to store information about a person, you might write:
struct Person {
var firstName: String
var lastName: String
var age: Int
}
This code declares a struct called “Person” that contains three properties: a first name, a last name, and an age. The properties are declared using the keyword “var”, followed by the property name and type. Once the struct is declared, you can create instances of it like this:
let john = Person(firstName: "John", lastName: "Smith", age: 25)
This code creates an instance of the Person struct, and sets the first name, last name, and age properties to “John”, “Smith”, and 25 respectively. You can then access these properties like this:
print(john.firstName) // Prints "John"
print(john.lastName) // Prints "Smith"
print(john.age) // Prints 25
In addition to declaring properties, you can also declare methods in a struct. Methods are functions that can be called on an instance of the struct. For example, you could add a method to the Person struct that prints out the full name of the person like this:
struct Person {
var firstName: String
var lastName: String
var age: Int
func fullName() -> String {
return "\(firstName) \(lastName)"
}
}
This code adds a method to the Person struct called “fullName”. This method takes no parameters and returns a string containing the person’s full name. You can then call this method like this:
print(john.fullName()) // Prints "John Smith"
Swift structs are a powerful and versatile tool for storing related pieces of information. With just a few lines of code, you can quickly create custom data types that can be used in your applications. In this article, we’ve looked at how to declare a struct in Swift, and how to add properties and methods to it. In the next article, we’ll look at how to use structs in more complex applications.