What is Structure in Swift ?

Yasir
2 min readJun 10, 2020

Author has explained what is structure and how you will write code in swift for structure.

Most programs that perform complex tasks benefit from higher levels of abstraction. In addition to an Int, String or Array, most programs use new types specific to the domain of the task at hand.

Structures are one of the named types in Swift that allow you to encapsulate related properties and behaviours. You can declare a new type, give it a name, and then use it in your code.

In structure , you can define your own data type . The variable and constant you use inside block of a particular structure is called as their properties . for example consider a structure named as location which could have two properties , x coordinate and and y coordinate .

Whenever you will use this location structure , you will define your properties as per your need .

Let’s see with code example for better understanding of it :

Image representing Structure syntax

Now in order to access the properties of these structure , you will use dot syntax . Let’s see it in our code below :

let storeLocation = Location(x: 2, y: 4)

now let’s print it : — — print(storeArea.radius)

Key Points

  • Structures are named types you can define and use in your code.
  • Structures are value types, which means their values are copied on assignment.
  • You use dot syntax to access the members of named types such as structures.
  • Named types can have their own variables and functions, which are called properties and methods.
  • Conforming to a protocol requires implementing the properties and methods required by that protocol.

--

--

Yasir

Exploring the Swift, SwiftUI, and Apple universe.