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
  • Benefits of using Functions
  • Things to Consider
  • Throwing Data back
  • Tuples
  • Copying Functions
  • Removing Parameter Name
  • Defining a Default Value for a Parameter
  • Checking Errors
  • Handling Function Failure with Optionals
  • Methods
  • Mutating Function
  • Functions as Parameters
  • Sample Codes
  • Sources
  • Videos
  • Articles / Documents

Was this helpful?

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

Functions

#code-smell #function #return #tuples #dictionary #method

Overview

Benefits of using Functions

  • Clearer code

    • Breaking big chunks of code into small pieces, so that you read and follow the code easily

    • Reusability in other functions, therefore you can write clearer code

  • Ease of change

    • When used in multiple places and other big functions, you change the behavior of the function from a place with ease

Things to Consider

  • Not to add more than 6 parameters

  • Splitting up into smaller functions for sake of readability

  • Whether those parameters are related to each other

Throwing Data back

If you want to return your own value from a function, you need to do two things:

  1. Write an arrow then a data type before your function’s opening brace, which tells Swift what kind of data will get sent back.

  2. Use the return keyword to send back your data.

// Standart if-else conditional
func greet(name: String) -> String {
    if name == "Taylor Swift" {
        return "Oh wow!"
    } else {
        return "Hello, \(name)"
    }
}

print(greet(name:"Sedat"))

print("-------------------------------------------------------------------")

// Ternary Conditional
func greet2(name: String) -> String {
    name == "Taylor Swift" ? "Oh wow!" : "Hello, \(name)"
}

print(greet2(name:"Sedat"))

print("-------------------------------------------------------------------")

// without return, it does not output the result outside of the function
func greet3(name: String) {
    if name == "Taylor Swift" {
        "Oh wow!"
    } else {
        "Hello, \(name)"
    }
}

print(greet3(name:"Sedat"))

Copying Functions

When you copy a function you do not use parenthesis ()

greetUser()
var greetCopy = greetUser
greetCopy()

When copying functions parameters will not come externally??? #learn

Removing Parameter Name

// With parameter name
func climbMountain0(name: String) {
    print("I'm going to climb \(name).")
}
climbMountain0(name:"Everest")

/*
print:

I'm going to climb Everest.

*/


print("-------------------------------------------------------------------")

// Without parameter name
func climbMountain1(_ name: String) {
    print("I'm going to climb \(name).")
}
climbMountain1("Everest")

/*
print:

I'm going to climb Everest.

*/

No difference in result at all.

Defining a Default Value for a Parameter

/* 
In "end: Int = 3" 3 is the default value. 
If nothing is defined for the "end" value so 3 is the value
*/

func printTimesTables(for number: Int, end: Int = 3) {
    for i in 1...end {
        print("\(i) x \(number) is \(i * number)")
    }
}

//printTimesTables(for: 5, end: 20)
printTimesTables(for: 8)

/*
print:

1 x 8 is 8
2 x 8 is 16
3 x 8 is 24

*/

Checking Errors

If a Function may throw an error, you must add error handling both to prevent crashing the app and to clarify the cause.

But keep in mind that adding a throw to function may cause many other problems. So it is better not to add them at the beginning. By the time you become familiar with the app itself and the throw mechanism, you will ad them carefully.

enum PasswordError: Error {
    case short, obvious
}

func checkPassword(_ password: String) throws -> String {
    if password.count < 5 {
        throw PasswordError.short
    }

    if password == "12345" {
        throw PasswordError.obvious
    }

    if password.count < 8 {
        return "OK"
    } else if password.count < 10 {
        return "Good"
    } else {
        return "Excellent"
    }
}


let string = "12345"

do {
    let result = try checkPassword(string)
    print("Password rating: \(result)")
} catch PasswordError.short {
    print("Please use a longer password.")
} catch PasswordError.obvious {
    print("I have the same combination on my luggage!")
} catch {
    print("There was an error: \(error.localizedDescription)")
}

/*
print:

I have the same combination on my luggage!

*/

Handling Function Failure with Optionals

If you only care about whether the function works or not, try may help. Otherwise do not use it.

If you want to know what those error are, and handle them uniquely, do not use "try?", but use do-catch-try block instead.

Methods

When Functions belong to Structs, they become Methods.

Sources

Mutating Function

  • // But why to change it? If we need to change it afterwards why we not define it as a var? #learn

Example 1: Resetting the the value set to its defaults

struct Canvas {
    var backgroundColor: Color?
    var foregroundColor: Color?
    var shapes = [Shape]()
    var images = [Image]()

    mutating func reset() {
        self = Canvas()
    }
}

Sources

Videos

Articles / Documents

Functions as Parameters

func makeArray(size: Int, using generator: () -> Int) -> [Int] {
    var numbers = [Int]()

    for _ in 0..<size {
        let newNumber = generator()
        numbers.append(newNumber)
    }

    return numbers  // output: [14, 17, 10, 11, 14]
}

let rolls = makeArray(size: 5) {  // output: [14, 17, 10, 11, 14]
    Int.random(in: 1...20)
}

print(rolls)
// print: [14, 17, 10, 11, 14]
func doImportantWork(first: () -> Void, second: () -> Void, third: () -> Void) {
    print("About to start first work")  // output: About to start first work
    first()
    print("About to start second work")  // output: About to start second work
    second()
    print("About to start third work")  // output: About to start third work
    third()
    print("Done!")  // output: Done!
}

doImportantWork {
    print("This is the first work")
} second: {
    print("This is the second work")
} third: {
    print("This is the third work")
}

/*
print:

About to start first work
This is the first work
About to start second work
This is the second work
About to start third work
This is the third work
Done!

*/
var payCash = {
    print("Here's the money.")
}
func buyClothes(item: String, using payment: () -> Void) {
    print("I'll take this \(item).")
    payment()
}
buyClothes(item: "jacket", using: payCash)

/*
print:

I'll take this jacket.
Here's the money.

*/

Sample Codes

func square(numbers: [Int]) {
    for number in numbers {
        let squared = number * number
        print("\(number) squared is \(squared).")
    }
}
square(numbers: [2, 3, 4])

/*
print:

2 squared is 4.
3 squared is 9.
4 squared is 16.

*/

Sources

Videos

Articles / Documents

PreviousStructsNextClosures

Last updated 2 years ago

Was this helpful?

Source: ,

Source: ,

Source: ,

Source: ,

Gives you ability to change a constant in a struct ().

Source:

Tuples
HWS
HWS
HWS
HWS
Hacking With Swift / What’s the difference between a function and a method?
Swift.org / Methods
HWS / 100days / 10
Swift by Sundel / Mutating and non-mutating Swift contexts
Hacking With Swift / Why do we need to mark some methods as mutating?
Hacking With Swift / 100 days / 10 - How to create your own structs
https://www.hackingwithswift.com/quick-start/beginners/how-to-accept-functions-as-parameters
https://www.hackingwithswift.com/100/swiftui/7
https://docs.swift.org/swift-book/LanguageGuide/Functions.html
https://www.kodeco.com/28797163-your-first-ios-swiftui-app-an-app-from-scratch/lessons/18
Swift.org / Methods
Page: Mutating Func