Structure, Protocol, and Class in Swift: The differences explained.

what is SWIFT?

what is the class in Swift?

  • properties
  • methods
  • subscripts
  • initializers
  • protocol conformances
  • extensions

what is structure in Swift?

  • properties
  • methods
  • subscripts
  • initializers
  • protocol conformances
  • extensions

what is protocol in Swift?

  • The protocol just holds the method or properties definition, not their actual body.
  • The protocol must specify whether the property will be gettable or gettable and settable.

Class vs Structure

  • Classes can inherit from another class, as you inherit from UIViewController 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.

Class vs Protocol

  • Classes are concrete things. While they might adopt protocols — i.e., say they implement the required properties and methods — they aren’t required to do that.
  • You can create objects from classes, whereas protocols are just typed definitions.
  • Protocols are like abstract definitions, whereas classes and structs are real things you can create.

Structure vs Protocol

  • In Swift, protocols provide communication across unrelated objects by defining methods and variables similar to those found in classes, enums, and structs.
  • Protocols are similar to interfaces, and Structs are similar to classes, except they are passed by value from one variable/function to the next.

--

--

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