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
  • For vs While
  • For Loop
  • Loop over a fixed range of numbers
  • Nested Loops
  • Loop without variable
  • Examples
  • While Loop
  • Skipping Loop items
  • Breaking in a point
  • Continue vs Break
  • FizzBuzz
  • Sources
  • Videos
  • Articles / Documents

Was this helpful?

  1. CODES

Loops

#loop #forloop #whileloop #forwhileloop #conditionals

Overview

  • Since you cannot change a number in "let", all the numbers should use "var"

For vs While

  • For: Finite (you give a range from the beginning)

  • While: Unpredictable (Until meets the target)

For Loop

example 1

let platforms = ["iOS", "macOS", "tvOS", "watchOS"]
// array

// os: loop variable
for os in platforms {
    print("Swift works great on \(os).")
}
// loop iteration

/*
print:
Swift works great on iOS.
Swift works great on macOS.
Swift works great on tvOS.
Swift works great on watchOS.
*/

Loop over a fixed range of numbers

for i in 1...12 {
    print("5 x \(i) is \(5 * i)")
}

/*
print:

5 x 1 is 5
5 x 2 is 10
5 x 3 is 15
5 x 4 is 20
5 x 5 is 25
5 x 6 is 30
5 x 7 is 35
5 x 8 is 40
5 x 9 is 45
5 x 10 is 50
5 x 11 is 55
5 x 12 is 60

*/

Nested Loops

In the below example, you may see that we used "up to" operator "..<" in order to limit the loop dynamically.

for i in 1..<4 {
    print("The \(i) times table:")

    for j in 1...2 {
        print("  \(j) x \(i) is \(j * i)")
    }

    print()
}

/*
print:

The 1 times table:
  1 x 1 is 1
  2 x 1 is 2

The 2 times table:
  1 x 2 is 2
  2 x 2 is 4

The 3 times table:
  1 x 3 is 3
  2 x 3 is 6

*/

Loop without variable

In some cases you may not need a variable. So you can define it as "_"

var lyric = "Haters gonna"

for _ in 1...5 { // her is variable is "_'
    lyric += " hate"
}

print(lyric)

Examples

var numbers = [1, 2, 3, 4, 5, 6]
for number in numbers {
    if number % 2 == 0 {
        print(number)
    }
}

/*
print:

2
4
6

*/
for i in 1...8 {
    if i < 3 {
        print("\(i) is a small number")
    }
}

/*
print:

1 is a small number
2 is a small number

*/

While Loop

Skipping Loop items

let filenames = ["me.jpg", "work.txt", "sophie.jpg", "logo.psd"]

for filename in filenames {
    if filename.hasSuffix(".jpg") == true {
        continue
    }

    print("Found picture: \(filename)")
}

/*
print:

Found picture: work.txt
Found picture: logo.psd

*/


// --------------

let filenames = ["me.jpg", "work.txt", "sophie.jpg", "logo.psd"]

for filename in filenames {
    if filename.hasSuffix(".jpg") == false {
        continue
    }

    print("Found picture: \(filename)")
}

/*
print:

Found picture: me.jpg
Found picture: sophie.jpg

*/

Breaking in a point

let number1 = 10
let number2 = 14
var multiples = [Int]()

for i in 1...100_000 {
    if i.isMultiple(of: number1) && i.isMultiple(of: number2) {
        multiples.append(i)

        if multiples.count == 10 {
            break
        }
    }
}

print(multiples)

// print: [70, 140, 210, 280, 350, 420, 490, 560, 630, 700]

Be aware of where you put the "Break". If you put it in the wrong place it will stop earlier.

var password = "1"
while true {
    password += "1"
    if password == "11111" {
        print("That's a terrible password.")
        break // exact point
    }
}
// print: That's a terrible password.

// --

var password = "1"
while true {
    password += "1"
    if password == "11111" {
        print("That's a terrible password.")
    }
    break // wrong place
}
// print: ""

Continue vs Break

Continue: As long as the result meets the criteria Continue

Break: Stop at a certain point

FizzBuzz

for i in 1...100 {
    if i % 3 != 0 { if i % 5 != 0 { print(i)} }
    if i % 3 == 0 { print("\(i) = Fizz") }
    if i % 5 == 0 { print("\(i) = Buzz") }
    if i % 3 == 0 { if i % 5 == 0 { print("\(i) = FizzBuzz") } }
}

/*
print:

1
2
3 = Fizz
4
5 = Buzz
6 = Fizz
7
8
9 = Fizz
10 = Buzz
11
12 = Fizz
13
14
15 = Fizz
15 = Buzz
15 = FizzBuzz
...

*//

Sources

Videos

Articles / Documents

PreviousTriggersNextPhysical Properties

Last updated 2 years ago

Was this helpful?

When we use continue we’re saying “I’m done with the current run of this loop” – Swift will skip the rest of the loop body, and go to the next item in the loop. But when we say break we’re saying “I’m done with this loop altogether, so get out completely.” That means Swift will skip the remainder of the body loop, but also skip any other loop items that were still to come. ()

HWS
https://www.hackingwithswift.com/100/swiftui/6