Structs in Swift

A struct is a data type that represents a custom value type in Swift. Structs are similar to classes, but they are simpler and more lightweight, and they are designed to be value types rather than reference types.

To define a struct in Swift, you use the struct keyword followed by the name of the struct and a set of braces that contain the struct’s properties and methods. Here is an example of how you can define a struct that represents a point in two-dimensional space:

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

This struct has two properties, x and y, that represent the coordinates of the point.

To create an instance of a struct, you use the struct’s name followed by the values for its properties in parentheses. Here is an example of how you can create a Point instance and access its properties:

var p = Point(x: 0, y: 0) 
print(p.x)  // prints 0 
print(p.y) // prints 0

In addition to defining properties, structs can also have methods, which are functions that are associated with the struct and can operate on its properties. Here is an example of how you can add a method to the Point struct that calculates the distance between two points:

struct Point { 
  var x: Int 
  var y: Int 
  
  func distance(to point: Point) -> Double { 
    let dx = Double(x - point.x) 
    let dy = Double(y - point.y) 
    
    return sqrt(dx * dx + dy * dy) 
  }
}

This method calculates the Euclidean distance between the current point and the point passed as an argument. To call this method, you would use the following code:

let p1 = Point(x: 0, y: 0) 
let p2 = Point(x: 3, y: 4) 
let d = p1.distance(to: p2) // d is equal to 5.0

Structs are an important feature of Swift, and they are commonly used to define custom value types for use in your code. For more information about structs and how to use them, you can refer to the Swift documentation.


Posted

in