Swift Dev Notes
SedatOnat.devAffiliated with SedatOnat.com
  • 👋Welcome to SedatOnat.dev
  • Learning Path
    • What to Learn?
    • How to Learn?
    • Useful Docs
      • Articles
      • Best Practices
      • Event Notes
        • Kodluyoruz
          • GIT - What is Markdown? How to use it?
        • NS Istanbul
          • Trendyol Super App
        • NS Spain
          • SoundCloud SwiftUI Experiences
        • Patika Events
          • Rust at a Glance
          • Being an IOS Developer
          • Mobil Uygulamamdan Nasıl Gelir Elde Ederim?
          • Tecrübeniz Yoksa Yazılımcı Portfolyosu Var: Peki Nasıl Olacak?
          • Yazılımda trend olan başlıklar nelerdir? Hype teknolojilere kapılmalı mıyım?
          • GitHub Profilinizin Önemi ve Geliştirmeniz İçin Öneriler
          • Patika LaunchPad
          • Özgür Kaya - Yazılım Test/Otomasyon Uzmanı Olmak
          • Türkay Ürkmez
          • Patika Derslerini Bitirsek Yazılımcı Olabilir Miyiz?
          • Performanslı ve Kaliteli Kod Yazmak
          • Yazılım Kariyeri İsteyenler: Nereden Başlamak Gerek?
          • Yazılımcılar dikkat burnout var
          • Yazılım Sektöründe Kariyer Tavsiyeleri
          • Front-End Kariyerine başlangıç
          • Öğrenmeniz gereken iş fırsatları: MNM Teknoloji ile PHP Symphony & Magento
          • Yurtdışı kariyer imkanı
          • Mezunlarımıza soralım: Bootcamp hızlandırmadan işe girmeye giden yolculuk
          • Savunma sektörünce mühendis olmak
          • Everything you need to know about technical interviews at top global companies
          • Java ve Framework 'leri - Akın Kaldıroğlu
          • React Native 'e dair Merak Edilenler
          • FAQs about being an Assistant at Patika
          • Career Journey - From Medical Faculty to Software Development
          • How to make your own game?
          • Altogic ile Backend uygulama geliştirmeyi baştan sonra anlayalım
          • Backend Developer Olmaya karar verdim, peki ya sonra?
          • Bir bilene soralım - .Net Framework 'e İlişkin merak ettikleriniz
          • Bir bilene soralım - Go Developer Olmak
          • Bir bilene soralım - Angular hakkında merak edilenler
          • Bu yaz kodlama konusunda kendime nasıl yatırımlar yapabilirim?
        • Tea-Coffee-Human
          • Where to Start for Coding?
        • Ugur Umutoglu
          • Nasıl Mobile Developer Oldum?
        • Yusuf Demirci
          • Nasıl iOS Developer Olarak İlk İşimi Buldum
          • Amsterdam 'da yazılımcı olmak
          • Nasıl iOS Developer Olurum
      • Insights
      • Job Application Notes
      • Media to use in Apps (Authorized)
      • Q&A
      • Quotes
      • Terminology
  • Before Starting
    • Xcode
      • Folder Attributes
      • Project Transfer
      • Shortcuts
      • Annotation
    • Version Control
      • Xcode Cloud
      • GIT
      • GitHub
      • GitLab
      • BitBucket
      • GitKraken
      • SourceTree
    • Swift
      • Declarative vs Imperative Languages
      • Things to Remember
    • Naming
  • DATABASES
    • Apple Database
      • CloudKit
      • CoreData
        • NSError
        • NSFetchRequest
        • NSManagedObject
        • NSMergePolicy
        • NSPredicate
        • FetchRequest
        • Relationships
        • .hasChanges
      • KeyChain
      • UserDefaults
    • 3rd Party Databases
      • AWS Amplify
      • Firebase
      • JSON
      • MySQL
      • ORM
      • Realm
      • SQL Lite
    • Database Comparison
  • Design Patterns
    • Alternatives
      • Clean Swift
      • MVC
      • MVI
      • MVVM
      • Uber RIB
      • Viper
    • Comparison
  • Model
    • Accessibility
    • Assets
    • Error Debugging
    • File Management
  • CODES
    • Pseudo Code
    • Frameworks
      • Cocoa
      • CodeScanner
      • CoreHaptics
      • CoreImage
      • Foundation
      • LocalAuthentication
      • MapKit
      • ?SwiftDate
      • Swinject
      • SwiftUI
      • UIKit
      • UserNotifications
    • APIs
      • AlamoFire
      • Apple URL Loading System
      • ChatGPT
      • Create ML
      • Wikipedia: Map Coordinates
    • Packages
    • Dependency Managers
      • Carthage
      • CocoaPods
      • SPM - Swift Package Manager
    • Libraries
      • RxSwift
      • KingFischer
      • ?SwiftLint
      • Moya
    • Main Pillars (Protocol, Class, Struct, etc.)
      • Protocols
        • OOP vs POP
        • Codable
        • Comparable
        • Equatable
        • Hashable
        • Identifiable
        • Observable
        • ObservableObject
        • PreviewProvider
        • Shape
        • View
      • Protocol vs Class
      • Classes
        • Adding Initializer to a ChildClass
        • Copying Classes
        • Deinitializer
        • Final Class
        • Override
        • Restart the Inheritance
        • Working with Variables
      • Class vs Struct
      • Structs
      • Functions
      • Closures
        • Closure: Escaping
    • Data Collectors
      • Arrays
        • Stride
      • Dictionaries
      • Enums (Enumerations)
      • Sets
      • Tuples
    • Properties / Data Containers
      • Constants
      • Variables
    • Property Wrappers
      • AppStorage
      • Binding
      • Dynamic Language Lookup
      • Environment
      • EnvironmentObject
      • FocusState
      • MainActor
      • Observed
      • Observed vs. State
      • ObservedObject
      • Published
      • State
      • State vs. StateObject
      • StateObject
    • Optionals
    • Data Types
      • Booleans
      • Date-Time
      • Numbers
      • Strings
      • Type Annotations
    • Operators
    • Conditionals
      • on...
      • Triggers
    • Loops
    • Physical Properties
      • Camera
      • Dynamic Island
      • Gestures
      • Haptics
      • Notifications
      • Sensors
        • Bluetooth
        • Camera
        • FaceID
        • GPS
        • Gyroscope
        • LIDAR
        • Microphone
        • NFC
        • TouchID / FingerPrint
        • WiFi
      • Speakers
    • Other Properties
      • Siri
      • Widgets
    • Code Pool
      • Text Modifiers
        • Adding and/or
        • .autocapitalization(.none)
        • .joined
        • Text Cases
        • TextEditor
        • Text Styles
      • Others
        • AssertionFailure
        • async/await
        • .constant
        • defer
        • .dismiss
        • extensions
        • Filtering
        • ForEach
        • .formatted()
        • init
        • isMultiple(of:)
        • map()
        • .random
        • .randomElement
        • .removeDublicates()
        • Result
        • self
        • .shuffled
        • .sink
        • SortDescriptor
        • Static let
        • Stepper
        • Super.
        • TabView()
        • Timer
  • View
    • Apple HIG
    • Design
      • Pool
      • Tools
    • Image and Graphic
      • CG - Core Graphics
        • CGAffineTransform
        • CGFloat
        • CGPoint
        • CGRect
        • CGSize
        • Path
      • CI - Core Image
        • CIContext
        • CIFilter
        • CIImage
      • Image
        • Image Modifiers...
          • .background
        • GeometryReader
      • NSObject
      • QR Code
    • Page Elements
      • Button
        • PushButton
      • CheckList
      • Confirmation Dialog
      • Context Menu
      • Display Modes
      • Divider
      • Drag and Drop List
      • Form
      • Grid
      • Group
      • GroupBox
      • Keyboard
      • Label
      • LazyView
      • List
        • .listStyle
      • NavigationLink
      • NavigationSplitView
      • NavigationStack
      • NavigationView
      • NavigationView vs NavigationStack
      • OutlineGroup
      • Picker
      • ProgressView()
      • ScrollView
      • Section
      • Shapes
        • Arc
        • Circle
        • Rectangle
      • sheet()
      • Slider
      • Stacks
      • TextField
      • Toggle
      • Toolbar
      • ViewBuilder
      • WindowGroup
    • View Modifiers
      • .alert
      • .alignment
      • .alignmenGuide
      • .animation
      • .blendMode
      • .blur()
      • .clipShape
      • Color
      • .contentShape
      • .disabled
      • .drawingGroup
      • .fill
      • .ignoreSafeArea
      • .inset
      • .isPresented
      • .navigationBarTitleDisplayMode
      • .navigationTitle
      • .overlay
      • .offset
      • .opacity
      • .padding
      • .position
      • .preferredColorScheme
      • .rotation
      • .scaleEffect
      • .searchable
      • stroke and strokeBorder
      • .task
      • .toggle
      • .trailingIcon
      • .transition
    • Reporting
    • Others
      • AsyncImage
      • Switching Views
      • Drawing
  • Solutions
    • Case Solutions
      • Solutions Pool
        • Adding to Favorites
      • Solutions for: Views
        • Solutions for: Button
        • Solutions for: Dark Mode Color Examples
        • Solutions for: Frame Modifier
        • Solutions for: Gooey Effect
        • Solutions for: List
        • Solutions for: Login Screen
        • Solutions for: Other Elements
        • Solutions for: Star Rating
        • Solutions for: Scrolling
        • Solutions for: Theme
    • Sample Project Pool
  • Testing
    • Debugging
      • Debug View Hierarchy (Xcode)
      • Profile your SwiftUI code and identify slow layouts
    • Testing CheckList
    • Unit Test
  • Documentation
    • GitBook
      • GitBook Page Template
      • GitBook Shortcuts
      • GitBook Documentation
    • MarkDown
  • Deploying and Publishing
    • Checklist
    • Deployment Processes
    • Publishing Processes
      • Reasons of Rejection
    • ASO - App Store Optimization
  • Kaizen
    • CI-CD
Powered by GitBook
On this page
  • Overview
  • Sample Codes
  • Technical Protocol Inheritance
  • Protocol Conformance
  • get / get set
  • self vs Self
  • Protocol Extensions
  • Opaque return types
  • Sources
  • Videos
  • Articles / Documents
  • See Also

Was this helpful?

  1. CODES
  2. Main Pillars (Protocol, Class, Struct, etc.)

Protocols

PreviousMain Pillars (Protocol, Class, Struct, etc.)NextOOP vs POP

Last updated 2 years ago

Was this helpful?

Overview

Swift is written as Protocol-Oriented Language.

In WWDC15 Apple suggested to always start with Protocol.

like SubClasses, Structs inherit data from Protocol. All the methods in Protocol must exist on Struct. And you cannot change data type of them. ()

Protocols are rules or minimum requirements (functions and variables) that classes and structs need to have (). We can add whatever we want.

let cannot be used in Protocols. Only var can be used.

Sample Codes

Example 1
protocol Vehicle {
    
    // Properties
    var name: String { get }  // car, bike, etc.
    var currentPassengers: Int { get set }  // number passengers in default
    
    // Methods
    func estimateTime(for distance: Int) -> Int
    func travel(distance: Int)
    
}

Technical Protocol Inheritance

Even if you not write the name of the protocol, swift understands and runs the protocol in background.

Protocol Conformance

struct stc_Name: cls_1, cls2, prc_1, prc_2 {
    // codes...
    }

if you want to add class to a struct, add prior to protocols.

get / get set

{ get } : Read

{ get set } : Read & Write

"set" Cannot be alone, always should be with get { get set }

self vs Self

self: Current Value

Self: Current Type (Int, Double, String, etc.)

Example 1
// Variant 1
extension Int {
    func squared() -> Int {
        self * self
    }
}

// Variant 2
extension Numeric {
    func squared() -> Self {
        self * self
    }
}

let wholeNumber = 5
print(wholeNumber.squared())

// print: 25

Protocol Extensions

They let us add functionality to many types all at once.

Example 1
extension Collection {
    var isNotEmpty: Bool {
        isEmpty == false
    }
}
Example 2
protocol Person {
    var name: String { get }
    func sayHello()
}

extension Person {
    func sayHello() {
        print("Hi, I'm \(name)")
    }
}

struct Employee: Person {
    let name: String
}

let taylor = Employee(name: "Taylor Swift")
taylor.sayHello()

// print: Hi I'm Taylor Swift

Protocols cannot have boddies, bodies can only be in extensions

protocol Building {
    var type: String { get }
    var rooms: Int { get }
    var cost: Int { get set }
    var agent: String { get set }
//    func printSummary()
    func printSummary() {  // Error: Protocol methods must not have bodies
        print("Talk to \(agent) to buy this \(type) for $\(cost).")
    }
}

//extension Building {
//    func printSummary() {
//        print("Talk to \(agent) to buy this \(type) for $\(cost).")
//    }
//}

Opaque return types

Sources

Videos

Articles / Documents

See Also

  • Protocol vs Class

Sources: ,

Sources: ,

Sources: ,

HWS
StiftfulThinking
HWS
HWS
HWS
WWDC15 - Protocol-Oriented Programming in Swift
Hacking with Swift / 100 days / 13 - Protocols and Extensions