{"id":2644,"date":"2026-02-05T08:24:09","date_gmt":"2026-02-05T08:24:09","guid":{"rendered":"https:\/\/demo.materiamedica.net\/demo6\/?p=2644"},"modified":"2026-02-05T08:24:42","modified_gmt":"2026-02-05T08:24:42","slug":"strings","status":"publish","type":"post","link":"https:\/\/demo.materiamedica.net\/demo6\/strings\/","title":{"rendered":"Chapter 30: Strings"},"content":{"rendered":"<h3 dir=\"auto\">1. What is a String in Swift? (the most important big picture)<\/h3>\n<p dir=\"auto\">A String is <strong>an ordered collection of characters<\/strong> \u2014 basically, text.<\/p>\n<p dir=\"auto\">But Swift strings are <strong>smarter and safer<\/strong> than in many other languages:<\/p>\n<ul dir=\"auto\">\n<li>They support <strong>full Unicode<\/strong> (emoji, Hindi, Telugu, Arabic, Chinese, Japanese, flags, skin tones\u2026)<\/li>\n<li>They count <strong>human-visible characters<\/strong> (not bytes or code points)<\/li>\n<li>Strings are <strong>value types<\/strong> \u2192 when you assign or pass them, a copy is made<\/li>\n<li>Strings are <strong>immutable<\/strong> when declared with let \u2192 you cannot change their content<\/li>\n<li>Strings are <strong>mutable<\/strong> when declared with var \u2192 you can append, replace, remove\u2026<\/li>\n<\/ul>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<div>\n<div><\/div>\n<\/div>\n<\/div>\n<div>\n<pre tabindex=\"0\"><code>let fixedMessage = \"Namaste, Hyderabad! \ud83c\udf36\ufe0f\"     \/\/ cannot be changed\r\nvar changeable = \"Hello\"                          \/\/ can be changed later<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">2. Creating Strings \u2013 all the common ways you\u2019ll actually use<\/h3>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>\/\/ 1. Simple string literal (most common)\r\nlet name = \"Sneha\"\r\n\r\n\/\/ 2. Empty string (very frequent)\r\nlet empty1 = \"\"\r\nlet empty2 = String()           \/\/ same thing\r\n\r\n\/\/ 3. Multi-line string (super clean \u2013 used all the time)\r\nlet aboutMe = \"\"\"\r\n    Hi, I'm learning Swift.\r\n    I live in Hyderabad.\r\n    My favorite emoji is \ud83d\ude0a\ud83d\ude80\r\n    \"\"\"\r\n\r\n\/\/ 4. String interpolation \u2013 #1 way to combine text + values\r\nlet age = 19\r\nlet city = \"Hyderabad\"\r\nlet intro = \"My name is \\(name), I am \\(age) years old, from \\(city).\"\r\n\r\n\/\/ 5. Raw string \u2013 ignores escape characters (very useful)\r\nlet regexPattern = #\"\\d{3}-\\d{3}-\\d{4}\"#\r\nlet filePath     = #\"C:\\Users\\Public\\Documents\\report.pdf\"#\r\nlet jsonExample  = #\"{ \"name\": \"Priya\", \"age\": 24 }\"#<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Quick tip<\/strong>: Use <strong>raw strings<\/strong> (#&#8221;&#8230;# ) whenever you have backslashes (\\) or quotes (&#8220;) \u2014 it saves you from writing lots of \\\\ and \\&#8221;.<\/p>\n<h3 dir=\"auto\">3. Most Important String Properties &amp; Methods (you will use these 100 times)<\/h3>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>let message = \"Swift is modern, safe, and fun! \ud83d\ude0a\ud83d\ude80\"\r\n\r\n\/\/ Length (counts characters, not bytes)\r\nprint(message.count)                \/\/ 35\r\n\r\n\/\/ Empty check (very common)\r\nprint(message.isEmpty)              \/\/ false\r\nprint(\"\".isEmpty)                   \/\/ true\r\n\r\n\/\/ Case conversion\r\nprint(message.uppercased())         \/\/ SWIFT IS MODERN, SAFE, AND FUN! \ud83d\ude0a\ud83d\ude80\r\nprint(message.lowercased())         \/\/ swift is modern, safe, and fun! \ud83d\ude0a\ud83d\ude80\r\n\r\n\/\/ Prefix \/ suffix check\r\nprint(message.hasPrefix(\"Swift\"))   \/\/ true\r\nprint(message.hasSuffix(\"\ud83d\ude80\"))      \/\/ true\r\n\r\n\/\/ Contains\r\nprint(message.contains(\"modern\"))   \/\/ true\r\nprint(message.contains(\"old\"))      \/\/ false\r\n\r\n\/\/ Replace (returns new string \u2013 original unchanged)\r\nlet updated = message.replacingOccurrences(of: \"fun\", with: \"powerful\")\r\nprint(updated)  \/\/ Swift is modern, safe, and powerful! \ud83d\ude0a\ud83d\ude80\r\n\r\n\/\/ Trim whitespace (very common for user input)\r\nlet dirtyInput = \"   hello   \"\r\nlet clean = dirtyInput.trimmingCharacters(in: .whitespacesAndNewlines)\r\nprint(\"[\\(clean)]\")   \/\/ [hello]<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">4. Looping over characters \u2013 very common &amp; very useful<\/h3>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>let word = \"\u0928\u092e\u0938\u094d\u0924\u0947 \ud83d\ude0a\"\r\n\r\nfor char in word {\r\n    print(char)\r\n}\r\n\r\n\/\/ Output:\r\n\/\/ \u0928\r\n\/\/ \u092e\r\n\/\/ \u0938\r\n\/\/ \u094d\r\n\/\/ \u0924\r\n\/\/ \u0947\r\n\/\/ (space)\r\n\/\/ \ud83d\ude0a<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Important things to understand:<\/strong><\/p>\n<ul dir=\"auto\">\n<li>You loop over <strong>grapheme clusters<\/strong> (what humans see as one character)<\/li>\n<li>&#8220;\ud83d\ude0a&#8221;.count == 1<\/li>\n<li>&#8220;\u0928\u092e\u0938\u094d\u0924\u0947&#8221;.count == 6 (even though it looks like 6 characters)<\/li>\n<\/ul>\n<p dir=\"auto\">This is <strong>different<\/strong> from many older languages that count bytes or Unicode scalars.<\/p>\n<h3 dir=\"auto\">5. String Interpolation \u2013 the modern, clean way to build text<\/h3>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>let product = \"iPhone 16 Pro\"\r\nlet price = 119900\r\nlet rating = 4.85\r\n\r\nlet description = \"\"\"\r\n    Product: \\(product)\r\n    Price:   \u20b9\\(price)\r\n    Rating:  \\(rating) \/ 5\r\n    \"\"\"\r\n\r\nprint(description)<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Advanced interpolation (very popular 2024\u20132026 style)<\/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>let temp = 36.7\r\n\r\nlet health = \"\"\"\r\n    Temperature: \\(temp, format: .number.precision(.fractionLength(1)))\u00b0C\r\n    Status:      \\(temp &gt; 38 ? \"Fever \ud83d\ude37\" : \"Normal \ud83c\udf21\ufe0f\")\r\n    \"\"\"\r\n\r\nprint(health)<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">6. Working with parts of a string (substrings, prefix, suffix)<\/h3>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>let fullName = \"Sneha Reddy\"\r\n\r\n\/\/ First character\r\nif let first = fullName.first {\r\n    print(\"First letter: \\(first)\")     \/\/ S\r\n}\r\n\r\n\/\/ Last character\r\nif let last = fullName.last {\r\n    print(\"Last letter: \\(last)\")       \/\/ y\r\n}\r\n\r\n\/\/ First 5 characters\r\nlet firstFive = fullName.prefix(5)      \/\/ \"Sneha\"\r\n\r\n\/\/ Everything after first space\r\nif let spaceIndex = fullName.firstIndex(of: \" \") {\r\n    let lastName = fullName[fullName.index(after: spaceIndex)...]\r\n    print(\"Last name: \\(lastName)\")     \/\/ Reddy\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Modern &amp; safe way (avoid force-unwrap)<\/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>let email = \"aarav@example.com\"\r\n\r\nif let atIndex = email.firstIndex(of: \"@\") {\r\n    let username = email[..&lt;atIndex]            \/\/ \"aarav\"\r\n    let domain   = email[email.index(after: atIndex)...]   \/\/ \"example.com\"\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">7. Very Common Real-Life Examples (you will write these)<\/h3>\n<h4 dir=\"auto\">Example 1 \u2013 Clean username validation<\/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 isValidUsername(_ input: String) -&gt; Bool {\r\n    let trimmed = input.trimmingCharacters(in: .whitespacesAndNewlines)\r\n    \r\n    return !trimmed.isEmpty &amp;&amp;\r\n           trimmed.count &gt;= 3 &amp;&amp;\r\n           trimmed.count &lt;= 20 &amp;&amp;\r\n           trimmed.allSatisfy { char in\r\n               char.isLetter || char.isNumber || char == \"_\" || char == \".\"\r\n           }\r\n}\r\n\r\nprint(isValidUsername(\"aarav_007\"))     \/\/ true\r\nprint(isValidUsername(\" a  \"))          \/\/ false<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h4 dir=\"auto\">Example 2 \u2013 Simple phone number formatting<\/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 formatIndianPhone(_ number: String) -&gt; String {\r\n    let digitsOnly = number.filter { $0.isNumber }\r\n    \r\n    guard digitsOnly.count == 10 else {\r\n        return number\r\n    }\r\n    \r\n    let prefix = \"+91 \"\r\n    let part1 = digitsOnly.prefix(5)\r\n    let part2 = digitsOnly.dropFirst(5)\r\n    \r\n    return prefix + part1 + \" \" + part2\r\n}\r\n\r\nprint(formatIndianPhone(\"9876543210\"))      \/\/ +91 98765 43210\r\nprint(formatIndianPhone(\"987 654 3210\"))    \/\/ same<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h4 dir=\"auto\">Example 3 \u2013 Password strength indicator<\/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 passwordStrength(_ password: String) -&gt; String {\r\n    guard !password.isEmpty else { return \"Too short\" }\r\n    \r\n    let lengthScore = password.count &gt;= 12 ? 3 : password.count &gt;= 8 ? 2 : 1\r\n    \r\n    let hasUpper  = !password.lowercased().elementsEqual(password)\r\n    let hasLower  = !password.uppercased().elementsEqual(password)\r\n    let hasDigit  = password.rangeOfCharacter(from: .decimalDigits) != nil\r\n    let hasSymbol = password.range(of: \"[!@#$%^&amp;*()_+=]\", options: .regularExpression) != nil\r\n    \r\n    let variety = [hasUpper, hasLower, hasDigit, hasSymbol].filter { $0 }.count\r\n    \r\n    let totalScore = lengthScore + variety\r\n    \r\n    switch totalScore {\r\n    case 6...7: return \"Very Strong \ud83d\udcaa\"\r\n    case 4...5: return \"Strong \ud83d\udc4d\"\r\n    case 2...3: return \"Medium \ud83d\ude10\"\r\n    default:    return \"Weak \ud83d\ude1f\"\r\n    }\r\n}\r\n\r\nprint(passwordStrength(\"Passw0rd!\"))     \/\/ Strong \ud83d\udc4d\r\nprint(passwordStrength(\"abc123\"))        \/\/ Medium \ud83d\ude10<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">8. Quick Summary \u2013 Most Important String Operations<\/h3>\n<div>\n<div dir=\"auto\">\n<table dir=\"auto\">\n<thead>\n<tr>\n<th data-col-size=\"md\">Goal<\/th>\n<th data-col-size=\"lg\">Best modern code example<\/th>\n<th data-col-size=\"lg\">Notes \/ Tip<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td data-col-size=\"md\">Build text with variables<\/td>\n<td data-col-size=\"lg\">&#8220;Hi \\(name), age: \\(age)&#8221;<\/td>\n<td data-col-size=\"lg\">Interpolation \u2013 #1 method<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Multi-line text<\/td>\n<td data-col-size=\"lg\">&#8220;&#8221;&#8221; \u2026 &#8220;&#8221;&#8221;<\/td>\n<td data-col-size=\"lg\">Cleanest way<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Length<\/td>\n<td data-col-size=\"lg\">text.count<\/td>\n<td data-col-size=\"lg\">Counts visible characters (emoji = 1)<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Empty check<\/td>\n<td data-col-size=\"lg\">text.isEmpty<\/td>\n<td data-col-size=\"lg\">Fast &amp; clear<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Upper \/ lower<\/td>\n<td data-col-size=\"lg\">text.uppercased(), text.lowercased()<\/td>\n<td data-col-size=\"lg\">Use for case-insensitive comparison<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Contains substring<\/td>\n<td data-col-size=\"lg\">text.contains(&#8220;word&#8221;)<\/td>\n<td data-col-size=\"lg\">Simple &amp; fast<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Replace text<\/td>\n<td data-col-size=\"lg\">text.replacingOccurrences(of: &#8220;old&#8221;, with: &#8220;new&#8221;)<\/td>\n<td data-col-size=\"lg\">Returns new string<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Trim whitespace<\/td>\n<td data-col-size=\"lg\">text.trimmingCharacters(in: .whitespacesAndNewlines)<\/td>\n<td data-col-size=\"lg\">Clean user input<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Loop over each character<\/td>\n<td data-col-size=\"lg\">for char in text { \u2026 }<\/td>\n<td data-col-size=\"lg\">Each char is a Character<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div><\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">9. Small Practice \u2013 Try these now<\/h3>\n<ol dir=\"auto\">\n<li>Create a welcome message with name, age, city using interpolation<\/li>\n<li>Write a function that checks if a string contains both &#8220;@&#8221; and &#8220;.&#8221; (basic email check)<\/li>\n<li>Format a 10-digit Indian phone number like: +91 XXXXX XXXXX<\/li>\n<\/ol>\n<p dir=\"auto\">Paste your code if you want feedback!<\/p>\n<p dir=\"auto\">What would you like to explore more deeply next?<\/p>\n<ul dir=\"auto\">\n<li>Advanced string manipulation (regular expressions, splitting, joining, prefix\/suffix)<\/li>\n<li>Strings + <strong>optionals<\/strong> (very common in real apps)<\/li>\n<li>Strings in <strong>SwiftUI<\/strong> (Text, formatting, markdown)<\/li>\n<li>Performance &amp; mutability (String vs NSMutableString vs Substring)<\/li>\n<li>Unicode, emoji, flags, skin tones in detail<\/li>\n<li>Or move to another topic (arrays, dictionaries, optionals, structs\u2026)<\/li>\n<\/ul>\n<p dir=\"auto\">Just tell me \u2014 we\u2019ll continue in the same detailed, patient, teacher-like style \ud83d\ude0a<\/p>\n","protected":false},"excerpt":{"rendered":"<p>1. What is a String in Swift? (the most important big picture) A String is an ordered collection of characters \u2014 basically, text. But Swift strings are smarter and safer than in many other&#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-2644","post","type-post","status-publish","format-standard","hentry","category-swift"],"_links":{"self":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2644","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=2644"}],"version-history":[{"count":2,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2644\/revisions"}],"predecessor-version":[{"id":2646,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2644\/revisions\/2646"}],"wp:attachment":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/media?parent=2644"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/categories?post=2644"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/tags?post=2644"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}