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?

What is a class in Swift?

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

What is a struct in Swift?

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

Class vs Struct

  • 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?

  • 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.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The Case for Using Custom Back Buttons in SwiftUI

Higher — Order Functions in Swift

iOS Core ML New Features WWDC2021

Creating a Pet Sticker App on iOS with Fritz Pet Segmentation

Maximize Privacy in iOS 14 — Part 1

Getting Started With iOS Animation (Part 3)

iOS: OAuth handler in Swift using Alamofire + AlamofireObjectMapper

Creating iOS Simulators for End-to-End Automation Tests

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
Niroshan Pushparaj

Niroshan Pushparaj

More from Medium

Singleton in Swift New

What are the Access Controllers in Swift?

iOS: How to upload photos and videos to Firebase Storage

Collection Types in Swift