Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Define Structures in Swift
Written by Team Kodeco

Structures in Swift are similar to classes, but they have a few key differences that make them useful in different situations.

A structure is a value type, which means that when you create an instance of a structure, it creates a new copy of the data. This can be useful when you want to make sure that changes to one instance of a structure don’t affect other instances.

Here’s an example of how to define a structure in Swift:

struct Point {
  var x: Double
  var y: Double
}

This creates a new structure called “Point” that has two properties, “x” and “y”.

You can create a new instance of a structure like this:

var myPoint = Point(x: 1.0, y: 2.0)

You can also access and modify the properties of a structure like this:

myPoint.x = 3.0
print(myPoint.x) // prints "3.0"

Here are some key points to remember about structures in Swift:

  • They are value types, which means that when you create an instance of a structure, it creates a new copy of the data.
  • They can have properties and methods just like classes.
  • They are useful when you want to make sure that changes to one instance of a structure don’t affect other instances.

The rest of this section of the cookbook will go into more detail about how to use structures (and classes) in Swift.

© 2024 Kodeco Inc.