Struct, Class and Protocol in Swift

credit — Treehouse Blog | Learn programming, design, and more — all online and on your own time. (teamtreehouse.com)

What is Swift?

Swift is a programming language developed by Apple Inc for iOS and OS X development. Swift adopts the best of C and Objective-C, without the constraints of C compatibility. Swift designers took idea from a variety of other famous languages, including Objective-C, Rust, Haskell, Ruby, Python, C#, and CLU.

What is a class in Swift?

A class is considered as a blueprint of objects. We use the class keyword to create a class in Swift. A class is a reference type which can contain:

  • properties
  • methods
  • subscripts
  • initializers
  • protocol conformances
  • extensions
class ClassName {
// class definition
}

What is a struct in Swift?

A struct is used to store variables of different data types. We use the struct keyword to create a class in Swift. A struct is a value type which, just like classes, can contain:

  • properties
  • methods
  • subscripts
  • initializers
  • protocol conformances
  • extensions
struct StructureName {
// structure definition
}

Class vs Struct

Structures and classes are general-purpose, flexible constructs that become the building blocks of your program’s code. You define properties and methods to add functionality to your structures and classes using the same syntax you use to define constants, variables, and functions.

  • Classes can inherit from another class, as you inherit from UI ViewController to create your own view controller subclass, but struct can’t.
  • Classes are reference types and structs are value types.
  • Typecasting enables you to check and interpret the type of a class instance at runtime.
  • In class, a Shared mutable state is required, and in struct, unique copies with an independent state are required.
  • In class, Objective-C interoperability is required and in a struct, the data is used in multiple threads.

What is a Protocol in Swift?

A protocol defines a blueprint of methods or properties that can then be adopted by classes. We use the protocol keyword to create a class in Swift.

  • The protocol just holds the method or properties definition, not their actual body.
  • In Swift, protocols provide communication across unrelated objects by defining methods and variables similar to those found in classes, enums, and structs.
  • The protocol must specify whether the property will be gettable or gettable and settable.
  • In Swift, to use a protocol, other classes must conform to it.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store