{"id":2744,"date":"2026-02-05T12:08:00","date_gmt":"2026-02-05T12:08:00","guid":{"rendered":"https:\/\/demo.materiamedica.net\/demo6\/?p=2744"},"modified":"2026-02-05T12:08:00","modified_gmt":"2026-02-05T12:08:00","slug":"chapter-79-swift-classes-objects","status":"publish","type":"post","link":"https:\/\/demo.materiamedica.net\/demo6\/chapter-79-swift-classes-objects\/","title":{"rendered":"Chapter 79: Swift Classes\/Objects"},"content":{"rendered":"<h3 dir=\"auto\">1. What is a class? What is an object? (the clearest possible explanation)<\/h3>\n<p dir=\"auto\"><strong>Class<\/strong> = the <strong>blueprint<\/strong> \/ <strong>recipe<\/strong> \/ <strong>template<\/strong> <strong>Object<\/strong> = one actual thing made from that blueprint<\/p>\n<p dir=\"auto\">Real-life analogy (the one that clicks for almost everyone):<\/p>\n<ul dir=\"auto\">\n<li><strong>Class<\/strong> = the design \/ blueprint of a smartphone (screen size, camera specs, battery type, how buttons work\u2026)<\/li>\n<li><strong>Object<\/strong> = one actual phone made from that blueprint \u2192 My iPhone 14 Pro \u2192 Your iPhone 15 \u2192 Your friend\u2019s iPhone 13<\/li>\n<\/ul>\n<p dir=\"auto\">Both phones follow the same <strong>design<\/strong> (same class), but each phone has its own:<\/p>\n<ul dir=\"auto\">\n<li>own phone number<\/li>\n<li>own photos<\/li>\n<li>own battery level<\/li>\n<li>own wallpaper<\/li>\n<\/ul>\n<p dir=\"auto\">That is the core idea:<\/p>\n<p dir=\"auto\"><strong>Class<\/strong> defines <strong>what<\/strong> every object of that type knows and can do. <strong>Object<\/strong> is one concrete instance with its own specific values.<\/p>\n<h3 dir=\"auto\">2. Creating a class \u2013 basic syntax<\/h3>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>class Person {\r\n    \/\/ Properties (data)\r\n    let name: String            \/\/ cannot be changed after creation\r\n    var age: Int                \/\/ can be changed later\r\n    var city: String?           \/\/ optional \u2013 may be nil\r\n    \r\n    \/\/ Initializer (how to create an object)\r\n    init(name: String, age: Int, city: String? = nil) {\r\n        self.name = name\r\n        self.age = age\r\n        self.city = city\r\n    }\r\n    \r\n    \/\/ Method (behavior)\r\n    func introduce() {\r\n        let cityText = city ?? \"somewhere\"\r\n        print(\"Hi, I'm \\(name), \\(age) years old, from \\(cityText)\")\r\n    }\r\n    \r\n    func haveBirthday() {\r\n        age += 1\r\n        print(\"Happy birthday! Now \\(name) is \\(age) years old \ud83c\udf82\")\r\n    }\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">3. Creating objects (instances) from the class<\/h3>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>\/\/ Create concrete objects\r\nlet rahul = Person(name: \"Rahul Verma\", age: 27, city: \"Bengaluru\")\r\nlet priya = Person(name: \"Priya Reddy\", age: 24)\r\n\r\n\/\/ Use them\r\nrahul.introduce()           \/\/ Hi, I'm Rahul Verma, 27 years old, from Bengaluru\r\npriya.introduce()           \/\/ Hi, I'm Priya Reddy, 24 years old, from somewhere\r\n\r\nrahul.haveBirthday()        \/\/ Happy birthday! Now Rahul Verma is 28 years old \ud83c\udf82\r\n\r\n\/\/ rahul and priya are different objects\r\nprint(rahul.age)            \/\/ 28\r\nprint(priya.age)            \/\/ 24 (unchanged)<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Important memory fact<\/strong>:<\/p>\n<ul dir=\"auto\">\n<li>rahul and priya are <strong>two separate objects<\/strong><\/li>\n<li>Changing one <strong>does not affect<\/strong> the other<\/li>\n<li>Classes are <strong>reference types<\/strong> \u2014 variables hold <strong>references<\/strong> (pointers) to the object in memory<\/li>\n<\/ul>\n<h3 dir=\"auto\">4. Real-life examples \u2014 classes you will actually write<\/h3>\n<h4 dir=\"auto\">Example 1 \u2013 BankAccount (classic encapsulation example)<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>class BankAccount {\r\n    let accountNumber: String\r\n    private var balance: Double = 0.0\r\n    \r\n    init(accountNumber: String, initialDeposit: Double) {\r\n        self.accountNumber = accountNumber\r\n        deposit(amount: initialDeposit)\r\n    }\r\n    \r\n    var currentBalance: Double {\r\n        balance\r\n    }\r\n    \r\n    func deposit(amount: Double) {\r\n        guard amount &gt; 0 else {\r\n            print(\"Deposit amount must be positive\")\r\n            return\r\n        }\r\n        balance += amount\r\n        print(\"Deposited \u20b9\\(amount). New balance: \u20b9\\(balance)\")\r\n    }\r\n    \r\n    func withdraw(amount: Double) -&gt; Bool {\r\n        guard amount &gt; 0 else {\r\n            print(\"Withdrawal amount must be positive\")\r\n            return false\r\n        }\r\n        guard amount &lt;= balance else {\r\n            print(\"Insufficient funds\")\r\n            return false\r\n        }\r\n        \r\n        balance -= amount\r\n        print(\"Withdrew \u20b9\\(amount). New balance: \u20b9\\(balance)\")\r\n        return true\r\n    }\r\n}\r\n\r\n\/\/ Real usage\r\nlet savingsAccount = BankAccount(accountNumber: \"SB-123456\", initialDeposit: 25000)\r\nsavingsAccount.deposit(amount: 10000)\r\n_ = savingsAccount.withdraw(amount: 5000)\r\nprint(\"Current balance: \u20b9\\(savingsAccount.currentBalance)\")\r\n\/\/ savingsAccount.balance = -100000 \/\/ \u2190 compile error \u2013 private!<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h4 dir=\"auto\">Example 2 \u2013 Simple Car class (inheritance + polymorphism)<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>class Car {\r\n    let brand: String\r\n    var currentSpeed: Double = 0.0\r\n    \r\n    init(brand: String) {\r\n        self.brand = brand\r\n    }\r\n    \r\n    func accelerate(to speed: Double) {\r\n        currentSpeed = speed\r\n        print(\"\\(brand) is now going at \\(speed) km\/h\")\r\n    }\r\n    \r\n    func honk() {\r\n        print(\"\\(brand) says: Beep beep!\")\r\n    }\r\n}\r\n\r\nclass ElectricCar: Car {\r\n    let batteryCapacity: Double\r\n    \r\n    init(brand: String, batteryCapacity: Double) {\r\n        self.batteryCapacity = batteryCapacity\r\n        super.init(brand: brand)\r\n    }\r\n    \r\n    override func accelerate(to speed: Double) {\r\n        super.accelerate(to: speed)\r\n        print(\"Quiet electric acceleration \u2013 zero emissions!\")\r\n    }\r\n    \r\n    override func honk() {\r\n        print(\"\\(brand) says: Beep boop! (electric sound)\")\r\n    }\r\n}\r\n\r\n\/\/ Polymorphism in action\r\nlet vehicles: [Car] = [\r\n    Car(brand: \"Maruti Swift\"),\r\n    ElectricCar(brand: \"Tata Nexon EV\", batteryCapacity: 40.5)\r\n]\r\n\r\nfor vehicle in vehicles {\r\n    vehicle.accelerate(to: 80)\r\n    vehicle.honk()\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">5. Very Common Beginner Mistakes &amp; Correct Habits<\/h3>\n<div>\n<div dir=\"auto\">\n<table dir=\"auto\">\n<thead>\n<tr>\n<th data-col-size=\"md\">Mistake<\/th>\n<th data-col-size=\"sm\">Wrong \/ Risky code<\/th>\n<th data-col-size=\"xl\">Correct \/ Better habit<\/th>\n<th data-col-size=\"lg\">Why?<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td data-col-size=\"md\">Using var for everything<\/td>\n<td data-col-size=\"sm\">var name: String everywhere<\/td>\n<td data-col-size=\"xl\">Default to let unless you actually reassign<\/td>\n<td data-col-size=\"lg\">let prevents accidental changes + better safety<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Force-unwrapping in class methods<\/td>\n<td data-col-size=\"sm\">self.user!.name<\/td>\n<td data-col-size=\"xl\">guard let user = user else { return }<\/td>\n<td data-col-size=\"lg\">Safer, better error handling<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Deep inheritance hierarchies<\/td>\n<td data-col-size=\"sm\">5+ levels of inheritance<\/td>\n<td data-col-size=\"xl\">Prefer composition or protocols<\/td>\n<td data-col-size=\"lg\">Deep trees become hard to maintain<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Making everything public<\/td>\n<td data-col-size=\"sm\">public class, public var everywhere<\/td>\n<td data-col-size=\"xl\">Use internal (default) or private when possible<\/td>\n<td data-col-size=\"lg\">Better encapsulation &amp; API control<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Mutating shared state without care<\/td>\n<td data-col-size=\"sm\">static var sharedBalance<\/td>\n<td data-col-size=\"xl\">Prefer dependency injection over singletons<\/td>\n<td data-col-size=\"lg\">Singletons make testing &amp; reasoning hard<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div><\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">6. Quick Summary \u2013 Classes vs Structs (the decision you make every day)<\/h3>\n<div>\n<div dir=\"auto\">\n<table dir=\"auto\">\n<thead>\n<tr>\n<th data-col-size=\"md\">Feature \/ Question<\/th>\n<th data-col-size=\"md\">Class (reference type)<\/th>\n<th data-col-size=\"md\">Struct (value type)<\/th>\n<th data-col-size=\"lg\">When most developers choose<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td data-col-size=\"md\">Identity matters (same object, same instance)<\/td>\n<td data-col-size=\"md\">Yes \u2014 two variables can point to same object<\/td>\n<td data-col-size=\"md\">No \u2014 copying creates independent value<\/td>\n<td data-col-size=\"lg\">Class when identity matters (shared state)<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Inheritance supported<\/td>\n<td data-col-size=\"md\">Yes<\/td>\n<td data-col-size=\"md\">No<\/td>\n<td data-col-size=\"lg\">Class when you need inheritance<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Can be used as key in Dictionary\/Set<\/td>\n<td data-col-size=\"md\">No (unless you implement Hashable carefully)<\/td>\n<td data-col-size=\"md\">Yes (if Hashable)<\/td>\n<td data-col-size=\"lg\">Struct almost always for value types<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Memory management<\/td>\n<td data-col-size=\"md\">Reference counting (ARC)<\/td>\n<td data-col-size=\"md\">Copied on write (Copy-on-Write for Array, Dict\u2026)<\/td>\n<td data-col-size=\"lg\">Struct safer for value semantics<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Thread safety (mutable shared state)<\/td>\n<td data-col-size=\"md\">Can cause problems<\/td>\n<td data-col-size=\"md\">Safer (each copy independent)<\/td>\n<td data-col-size=\"lg\">Struct preferred in modern Swift<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Typical use in SwiftUI<\/td>\n<td data-col-size=\"md\">ObservableObject \/ @StateObject<\/td>\n<td data-col-size=\"md\">@State, @ObservedObject (structs)<\/td>\n<td data-col-size=\"lg\">Structs for most data models<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div><\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Modern Swift recommendation (2025\u20132026)<\/strong>:<\/p>\n<blockquote dir=\"auto\">\n<p dir=\"auto\">Use <strong>struct<\/strong> by default for almost everything Use <strong>class<\/strong> only when you need:<\/p>\n<ul dir=\"auto\">\n<li>reference semantics (shared mutable state)<\/li>\n<li>inheritance<\/li>\n<li>Objective-C interop<\/li>\n<li>identity comparison (===)<\/li>\n<\/ul>\n<\/blockquote>\n<h3 dir=\"auto\">7. Small Practice \u2013 Try these<\/h3>\n<ol dir=\"auto\">\n<li>Create a Person class with:\n<ul dir=\"auto\">\n<li>let name: String<\/li>\n<li>var age: Int<\/li>\n<li>method haveBirthday() that increases age<\/li>\n<\/ul>\n<\/li>\n<li>Create a BankAccount class like the example above\n<ul dir=\"auto\">\n<li>private balance<\/li>\n<li>deposit &amp; withdraw methods<\/li>\n<li>read-only currentBalance<\/li>\n<\/ul>\n<\/li>\n<li>Create ElectricCar that inherits from Car\n<ul dir=\"auto\">\n<li>override honk() to say something electric<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n<p dir=\"auto\">Paste your code here if you want feedback or want to see more polished versions!<\/p>\n<p dir=\"auto\">What would you like to explore next?<\/p>\n<ul dir=\"auto\">\n<li><strong>Struct vs Class<\/strong> \u2014 detailed comparison &amp; decision guide<\/li>\n<li><strong>Inheritance<\/strong> vs <strong>composition<\/strong> (modern preference)<\/li>\n<li><strong>Protocol-oriented programming<\/strong> (POP)<\/li>\n<li><strong>Access control<\/strong> (private, fileprivate, internal, public, open)<\/li>\n<li>OOP in <strong>SwiftUI<\/strong> (ObservableObject, @StateObject\u2026)<\/li>\n<li>Or move to another topic (optionals, arrays, closures, switch\u2026)<\/li>\n<\/ul>\n<p dir=\"auto\">Just tell me \u2014 we\u2019ll continue in the same clear, detailed, patient style \ud83d\ude0a<\/p>\n","protected":false},"excerpt":{"rendered":"<p>1. What is a class? What is an object? (the clearest possible explanation) Class = the blueprint \/ recipe \/ template Object = one actual thing made from that blueprint Real-life analogy (the one&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[76],"tags":[],"class_list":["post-2744","post","type-post","status-publish","format-standard","hentry","category-swift"],"_links":{"self":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2744","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/comments?post=2744"}],"version-history":[{"count":1,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2744\/revisions"}],"predecessor-version":[{"id":2745,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2744\/revisions\/2745"}],"wp:attachment":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/media?parent=2744"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/categories?post=2744"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/tags?post=2744"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}