{"id":2728,"date":"2026-02-05T11:44:29","date_gmt":"2026-02-05T11:44:29","guid":{"rendered":"https:\/\/demo.materiamedica.net\/demo6\/?p=2728"},"modified":"2026-02-05T11:44:29","modified_gmt":"2026-02-05T11:44:29","slug":"chapter-71-functions","status":"publish","type":"post","link":"https:\/\/demo.materiamedica.net\/demo6\/chapter-71-functions\/","title":{"rendered":"Chapter 71: Functions"},"content":{"rendered":"<h3 dir=\"auto\">1. What is a function? (the most honest explanation)<\/h3>\n<p dir=\"auto\">A <strong>function<\/strong> is a named piece of reusable code that:<\/p>\n<ul dir=\"auto\">\n<li>takes <strong>zero or more inputs<\/strong> (parameters)<\/li>\n<li>does some work<\/li>\n<li>optionally <strong>returns<\/strong> a result<\/li>\n<\/ul>\n<p dir=\"auto\">Think of a function as a <strong>small worker<\/strong> inside your program:<\/p>\n<ul dir=\"auto\">\n<li>You give it <strong>instructions<\/strong> (parameters)<\/li>\n<li>It <strong>does its job<\/strong><\/li>\n<li>It hands back <strong>a result<\/strong> (or nothing)<\/li>\n<\/ul>\n<p dir=\"auto\">Functions are the <strong>building blocks<\/strong> of every non-trivial program.<\/p>\n<h3 dir=\"auto\">2. The basic syntax \u2014 all the common forms<\/h3>\n<h4 dir=\"auto\">Form 1 \u2013 Simplest function (no parameters, no return)<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>func sayHello() {\r\n    print(\"Hello, Hyderabad! \ud83c\udf36\ufe0f\")\r\n}\r\n\r\n\/\/ Call it\r\nsayHello()          \/\/ prints: Hello, Hyderabad! \ud83c\udf36\ufe0f<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h4 dir=\"auto\">Form 2 \u2013 With parameters (most common)<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>func greet(name: String) {\r\n    print(\"Namaste, \\(name)! \ud83d\udc4b\")\r\n}\r\n\r\ngreet(name: \"Rahul\")        \/\/ Namaste, Rahul! \ud83d\udc4b\r\ngreet(name: \"Priya\")        \/\/ Namaste, Priya! \ud83d\udc4b<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Important<\/strong>: In Swift, when you <strong>call<\/strong> the function, you <strong>must label<\/strong> the arguments (unless you use _ \u2014 more later).<\/p>\n<h4 dir=\"auto\">Form 3 \u2013 With return value<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>func add(_ a: Int, _ b: Int) -&gt; Int {\r\n    return a + b\r\n}\r\n\r\nlet sum = add(7, 8)         \/\/ 15\r\nprint(sum)<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Shorthand return<\/strong> (very common &amp; clean):<\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>func multiply(_ a: Int, _ b: Int) -&gt; Int {\r\n    a * b                   \/\/ implicit return \u2014 no `return` keyword needed\r\n}\r\n\r\nprint(multiply(6, 7))       \/\/ 42<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h4 dir=\"auto\">Form 4 \u2013 Multiple parameters + labels<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>func introduce(name: String, age: Int, city: String) {\r\n    print(\"\\(name) is \\(age) years old and lives in \\(city).\")\r\n}\r\n\r\nintroduce(name: \"Sneha\", age: 24, city: \"Hyderabad\")<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\">You can make some labels <strong>external<\/strong> and some <strong>internal<\/strong>:<\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>func greet(person name: String, from city: String) {\r\n    print(\"Namaste \\(name)! Greetings from \\(city)!\")\r\n}\r\n\r\ngreet(person: \"Aarav\", from: \"Bengaluru\")<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">3. Real-life examples \u2014 functions you will actually write<\/h3>\n<h4 dir=\"auto\">Example 1 \u2013 Format currency (very common)<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>func formatIndianCurrency(_ amount: Double) -&gt; String {\r\n    let formatter = NumberFormatter()\r\n    formatter.numberStyle = .currency\r\n    formatter.currencyCode = \"INR\"\r\n    formatter.currencySymbol = \"\u20b9\"\r\n    formatter.maximumFractionDigits = 2\r\n    \r\n    return formatter.string(from: NSNumber(value: amount)) ?? \"\u20b90.00\"\r\n}\r\n\r\nlet price = 12499.99\r\nprint(\"Price: \\(formatIndianCurrency(price))\")      \/\/ Price: \u20b912,499.99<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h4 dir=\"auto\">Example 2 \u2013 Validate email (very common in forms)<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>func isValidEmail(_ email: String) -&gt; Bool {\r\n    let emailRegex = \"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\\\.[A-Za-z]{2,64}\"\r\n    let emailPredicate = NSPredicate(format: \"SELF MATCHES %@\", emailRegex)\r\n    \r\n    return emailPredicate.evaluate(with: email)\r\n}\r\n\r\nlet testEmails = [\r\n    \"rahul@example.com\",\r\n    \"priya@gmail.com\",\r\n    \"invalid-email\",\r\n    \"a@b.c\",\r\n    \"test@company.co.in\"\r\n]\r\n\r\nfor email in testEmails {\r\n    print(\"\\(email): \\(isValidEmail(email) ? \"valid\" : \"invalid\")\")\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h4 dir=\"auto\">Example 3 \u2013 Calculate discount (business logic)<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>func calculateFinalPrice(\r\n    basePrice: Double,\r\n    quantity: Int,\r\n    discountPercent: Double = 0,\r\n    taxRate: Double = 0.18\r\n) -&gt; Double {\r\n    let subtotal = basePrice * Double(quantity)\r\n    let discountAmount = subtotal * (discountPercent \/ 100)\r\n    let priceAfterDiscount = subtotal - discountAmount\r\n    let taxAmount = priceAfterDiscount * taxRate\r\n    \r\n    return priceAfterDiscount + taxAmount\r\n}\r\n\r\nlet final = calculateFinalPrice(\r\n    basePrice: 1499.99,\r\n    quantity: 2,\r\n    discountPercent: 10,\r\n    taxRate: 0.18\r\n)\r\n\r\nprint(\"Final amount: \u20b9\\(String(format: \"%.2f\", final))\")<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h4 dir=\"auto\">Example 4 \u2013 Filter active users (very common in social \/ admin apps)<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>struct User {\r\n    let id: Int\r\n    let name: String\r\n    let isActive: Bool\r\n    let lastActive: Date?\r\n}\r\n\r\nfunc activeUsers(from users: [User], since daysAgo: Int = 30) -&gt; [String] {\r\n    let cutoff = Date().addingTimeInterval(-Double(daysAgo * 24 * 60 * 60))\r\n    \r\n    return users\r\n        .filter { $0.isActive || ($0.lastActive ?? .distantPast) &gt;= cutoff }\r\n        .map { $0.name }\r\n}\r\n\r\nlet users = [\r\n    User(id: 1, name: \"Rahul\", isActive: true, lastActive: nil),\r\n    User(id: 2, name: \"Priya\", isActive: false, lastActive: Date().addingTimeInterval(-15*24*60*60)),\r\n    User(id: 3, name: \"Aarav\", isActive: false, lastActive: Date().addingTimeInterval(-45*24*60*60))\r\n]\r\n\r\nlet activeNames = activeUsers(from: users)\r\nprint(\"Active users:\", activeNames)<\/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=\"xl\">Wrong \/ Risky code<\/th>\n<th data-col-size=\"lg\">Correct \/ Better habit<\/th>\n<th data-col-size=\"md\">Why?<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td data-col-size=\"md\">Forgetting to return value<\/td>\n<td data-col-size=\"xl\">func add(a: Int, b: Int) -&gt; Int { a + b }<\/td>\n<td data-col-size=\"lg\">return a + b or use implicit return<\/td>\n<td data-col-size=\"md\">Compile error if missing<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Using var for parameters unnecessarily<\/td>\n<td data-col-size=\"xl\">func greet(name: String) { name = &#8220;Hello&#8221; + name }<\/td>\n<td data-col-size=\"lg\">Parameters are let by default \u2014 good!<\/td>\n<td data-col-size=\"md\">Prevents accidental mutation<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Force-unwrapping in functions<\/td>\n<td data-col-size=\"xl\">func getName(user: User?) -&gt; String { user!.name }<\/td>\n<td data-col-size=\"lg\">guard let user else { return &#8220;Guest&#8221; }<\/td>\n<td data-col-size=\"md\">Safer, better error handling<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Too many parameters<\/td>\n<td data-col-size=\"xl\">func createUser(name, age, city, email, phone, \u2026)<\/td>\n<td data-col-size=\"lg\">Use struct \/ DTO instead<\/td>\n<td data-col-size=\"md\">More readable, easier to extend<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Side-effects in pure functions<\/td>\n<td data-col-size=\"xl\">func calculateTotal(price: Double) -&gt; Double { print(&#8220;Calculating\u2026&#8221;); return price * 1.18 }<\/td>\n<td data-col-size=\"lg\">Keep functions pure when possible<\/td>\n<td data-col-size=\"md\">Easier to test, predict<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div><\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">6. Quick Reference \u2013 Function patterns you will use most<\/h3>\n<div>\n<div dir=\"auto\">\n<table dir=\"auto\">\n<thead>\n<tr>\n<th data-col-size=\"sm\">Goal<\/th>\n<th data-col-size=\"lg\">Most idiomatic style<\/th>\n<th data-col-size=\"lg\">Notes \/ Tip<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td data-col-size=\"sm\">Simple action (no return)<\/td>\n<td data-col-size=\"lg\">func log(message: String) { print(message) }<\/td>\n<td data-col-size=\"lg\">Side-effect functions<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"sm\">Pure calculation<\/td>\n<td data-col-size=\"lg\">func add(_ a: Int, _ b: Int) -&gt; Int { a + b }<\/td>\n<td data-col-size=\"lg\">Implicit return, no return keyword<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"sm\">Optional return<\/td>\n<td data-col-size=\"lg\">func findUser(id: Int) -&gt; User? { \u2026 }<\/td>\n<td data-col-size=\"lg\">Return nil when not found<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"sm\">Multiple outputs<\/td>\n<td data-col-size=\"lg\">func divide(_ a: Double, by b: Double) -&gt; (quotient: Double, remainder: Double)<\/td>\n<td data-col-size=\"lg\">Use tuple or custom struct<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"sm\">Default parameters<\/td>\n<td data-col-size=\"lg\">func greet(name: String = &#8220;Guest&#8221;) { \u2026 }<\/td>\n<td data-col-size=\"lg\">Very common for optional arguments<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"sm\">Throwing function<\/td>\n<td data-col-size=\"lg\">func loadData() throws -&gt; Data { \u2026 }<\/td>\n<td data-col-size=\"lg\">Use try, do-catch when calling<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div><\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">7. Small Practice \u2013 Try these<\/h3>\n<ol dir=\"auto\">\n<li>Write a function greetUser(name: String, age: Int) that prints: &#8220;Namaste [name]! You are [age] years old.&#8221;<\/li>\n<li>Write a function calculateDiscountedPrice(original: Double, discountPercent: Double = 10) -&gt; Double<\/li>\n<li>Write a function isStrongPassword(_ password: String) -&gt; Bool that checks:\n<ul dir=\"auto\">\n<li>length \u2265 8<\/li>\n<li>has at least one uppercase<\/li>\n<li>has at least one number<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n<p dir=\"auto\">Paste your code here if you want feedback or want to see even cleaner versions!<\/p>\n<p dir=\"auto\">What would you like to explore next?<\/p>\n<ul dir=\"auto\">\n<li>Functions with <strong>default parameters<\/strong> &amp; <strong>variadic parameters<\/strong> (\u2026)<\/li>\n<li><strong>Throwing functions<\/strong> (throws, try, do-catch)<\/li>\n<li><strong>Function types<\/strong> &amp; <strong>closures<\/strong> (very important)<\/li>\n<li><strong>Nested functions<\/strong> &amp; <strong>higher-order functions<\/strong><\/li>\n<li>Functions in <strong>SwiftUI<\/strong> (action closures, view builders)<\/li>\n<li>Or move to another topic (optionals, arrays, switch, loops\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 function? (the most honest explanation) A function is a named piece of reusable code that: takes zero or more inputs (parameters) does some work optionally returns a result Think of&#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-2728","post","type-post","status-publish","format-standard","hentry","category-swift"],"_links":{"self":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2728","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=2728"}],"version-history":[{"count":1,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2728\/revisions"}],"predecessor-version":[{"id":2729,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2728\/revisions\/2729"}],"wp:attachment":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/media?parent=2728"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/categories?post=2728"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/tags?post=2728"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}