Skip to content

Instantly share code, notes, and snippets.

@onlyyoujack
Forked from kharrison/String.swift
Created December 15, 2015 06:44
Show Gist options
  • Save onlyyoujack/89df3f78a5a4d112025a to your computer and use it in GitHub Desktop.
Save onlyyoujack/89df3f78a5a4d112025a to your computer and use it in GitHub Desktop.
Swift String Playground Examples
// Swift Standard Librray - String
// ====
// Initializing a String
// ====
var emptyString = "" // Empty String
var stillEmpty = String() // Another empty String
let helloWorld = "Hello World!" // String inferred
let a = String(true) // from boolean: "true"
let b: Character = "A" // Explicit type required to create a Character
let c = String(b) // from character "A"
let d = String(3.14) // from Double "3.14"
let e = String(1000) // from Int "1000"
let f = "Result = \(d)" // Interpolation "Result = 3.14"
let g = "\u{2126}" // Unicode Ohm sign Ω
let h = String(count:3, repeatedValue:b) // Repeated character "AAA"
// Strings are value types that are copied when
// assigned or passed to a function.
// The copy is performed lazily on mutation
var aString = "Hello"
var bString = aString
bString += " World!"
print("\(aString)") // "Hello\n"
// ===
// Testing for empty String
// ===
emptyString.isEmpty // true
// ===
// Testing for equality
// Swift is Unicode correct so the equality
// operator checks for Unicode canonical equivalence
// ===
let spain = "España"
let tilde = "\u{303}"
let country = "Espan" + "\(tilde)" + "a"
if country == spain {
print("Matched!") // "Matched!\n"
}
// Order
if "aaa" < "bbb" {
print("aaa")
}
// Testing for suffix/prefix
country.hasPrefix("E") // true
country.hasSuffix("aña") // true
// Converting to upper/lower case
let mixedCase = "AbcDef"
let upper = mixedCase.uppercaseString // "ABCDEF"
let lower = mixedCase.lowercaseString // "abcdef"
// Views
// Properties provide collection views with
// different representations
country.characters // characters
country.unicodeScalars // Unicode scalar 21-bit codes
country.utf16 // UTF-16 encoding
country.utf8 // UTF-8 encoding
// Counting
// count is implemented on the collection view
print("\(spain) has \(spain.characters.count) characters")
print("Unicode scalar has \(spain.unicodeScalars.count) characters")
print("UTF 16 has \(spain.utf16.count) characters")
print("UTF 8 has \(spain.utf8.count) characters")
// Using Index to traverse a collection
// Each of the collection views has an Index that
// you use to traverse the collection.
// You cannot use String[10] to access
// Enumerating each item in a collection
var sentence = "Never odd or even"
for character in sentence.characters {
print(character)
}
// Indices
// startIndex == endIndex for an empty string
// endIndex is beyond the end of string
// error if index out of bounds
let cafe = "café"
cafe.startIndex // 0
cafe.endIndex // 4 - after last char
// Use the index to access the collection
// Use successor or predecessor to get next value
// Use advancedBy(n) to jump
// Direct access not possible e.g. cafe[0] is an error
cafe[cafe.startIndex] // "c"
cafe[cafe.startIndex.successor()] // "a"
cafe[cafe.startIndex.successor().successor()] // "f"
// Note that cafe[endIndex] is a run time error
cafe[cafe.endIndex.predecessor()] // "é"
cafe[cafe.startIndex.advancedBy(2)] // "f"
// indices property returns a range for all chars in String
for index in cafe.characters.indices {
print(cafe[index])
}
// Use distance to convert index to integer
// You cannot use an index from one String to access
// a different string.
let word1 = "ABCDEF"
let word2 = "012345"
let indexC = word1.startIndex.advancedBy(2)
let distance = word1.startIndex.distanceTo(indexC) // 2
let digit = word2[word2.startIndex.advancedBy(distance)] // "2"
// Using a range
// A range has a start and end index
let fqdn = "useyourloaf.com"
let rangeOfTLD = Range(start: fqdn.endIndex.advancedBy(-3), end: fqdn.endIndex)
let tld = fqdn[rangeOfTLD] // "com"
// Alternate creation of range (... or ..< syntax)
let rangeOfDomain = fqdn.startIndex..<fqdn.endIndex.advancedBy(-4)
let domain = fqdn[rangeOfDomain] // "useyourloaf"
// Getting a substring using index or range
var template = "<<<Hello>>>"
let indexStartOfText = template.startIndex.advancedBy(3)
let indexEndOfText = template.endIndex.advancedBy(-3)
let subString1 = template.substringFromIndex(indexStartOfText)
let subString2 = template.substringToIndex(indexEndOfText)
let rangeOfHello = indexStartOfText...indexEndOfText
let subString3 = template.substringWithRange(rangeOfHello)
let subString4 = template.substringWithRange(indexStartOfText..<indexEndOfText)
// Prefix and suffix substrings
// Quick ways to get or drop prefix or suffix
let digits = "0123456789"
let tail = String(digits.characters.dropFirst()) // "123456789"
let less = String(digits.characters.dropFirst(3)) // "23456789"
let head = String(digits.characters.dropLast(3)) // "0123456"
let prefix = String(digits.characters.prefix(2)) // "01"
let suffix = String(digits.characters.suffix(2)) // "89"
let index4 = digits.startIndex.advancedBy(4)
let thru4 = String(digits.characters.prefixThrough(index4)) // "01234"
let upTo4 = String(digits.characters.prefixUpTo(index4)) // "0123"
let from4 = String(digits.characters.suffixFrom(index4)) // "456789"
// Inserting/removing
// Insert a character at index
var stars = "******"
stars.insert("X", atIndex: stars.startIndex.advancedBy(3)) // "***X***"
// Insert a string at index (converting to characters)
stars.insertContentsOf("YZ".characters, at: stars.endIndex.advancedBy(-3)) // "***XYZ***"
// Replace with Range
let xyzRange = stars.startIndex.advancedBy(3)..<stars.endIndex.advancedBy(-3)
stars.replaceRange(xyzRange, with: "ABC") // "***ABC***"
// Append
var message = "Welcome"
message += " Tim" // "Welcome Tim"
message.appendContentsOf("!!!") // "Welcome Tim!!!
// Remove and return element at index
// This invalidates any indices you may have on the string
var grades = "ABCDEF"
let ch = grades.removeAtIndex(grades.startIndex) // "A"
print(grades) // "BCDEF"
// Remove Range
// Invalidates all indices
var sequences = "ABA BBA ABC"
let midRange = sequences.startIndex.advancedBy(4)...sequences.endIndex.advancedBy(-4)
sequences.removeRange(midRange) // "ABA ABC"
// Import Foundation if you want to bridge to NSString
import Foundation
let welcome = "hello world!"
welcome.capitalizedString // "Hello World!"
// Searching
let text = "123045780984"
if let rangeOfZero = text.rangeOfString("0",options: NSStringCompareOptions.BackwardsSearch) {
// Found a zero
let suffix = String(text.characters.suffixFrom(rangeOfZero.endIndex)) // "984"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment