Swift String and Character
Created By:Debasis Das (Jan 2016)
In this post we will test the Swift String functions and see examples of expected behaviors
- Strings are ordered collections of characters
- Swift Strings are represented by the “String” Type
- Swift String literal syntax is similar to C. String concatenation is as simple as adding two string using the + operator
- String mutability is controlled by choosing between a variable and a constant using the “var” and “let”
- String Interpolation – We can use strings to insert contants, variables, literals and expressions to form a longer string
- Swift’s String type is bridged with Foundation’s NSString Class.
- Swift String is a value type. It means when a new string is created the value is copied when it is passed to a function or method or when it assigned to a constant or a variable. A new copy is created and assigned.
Swift String Literals
func stringMethod1(){ //String literal is a fixed sequence of textual characters let nameString = "John Doe"; print(nameString); //John Doe //nameString = "Jane Doe" //This line will give an compiler error as the nameString is defined as a constant //Note: A constant string cannot be modified //Creating an empty string let emptyString = "" var anotherEmptyString = String() print("******** \n \(emptyString) \n********") /* ******** ******** */ }
Swift String Mutability
func stringMethod2(){ var nameString = "John Doe" print(nameString) //John Doe nameString += " is a placeholder name for a man whose true identity is unknown" print(nameString) //John Doe is a placeholder name for a man whose true identity is unknown }
Swift Strings and Characters
func stringMethod3(){
let characterString = "ABCD"
for character in characterString.characters{
print (character)
}
/*
A
B
C
D
*/
Creating a Swift String by passing an array of Character Values
let characterArray:[Character] = ["J","o","h","n"]
let nameString = String(characterArray)
print (nameString) //John
Swift Concatenating String
let string1 = "Hello " let string2 = "World !" var string3 = string1 + string2; print(string3) //Hello World ! string3 += " This is Swift 2.0" print(string3) //Hello World ! This is Swift 2.0 string3.appendContentsOf(" and this is better than Swift 1.2") print (string3) //Hello World ! This is Swift 2.0 and this is better than Swift 1.2 string3.append(Character("!")) print(string3) //Hello World ! This is Swift 2.0 and this is better than Swift 1.2!
Swift String Interpolation
String interpolation is a way to construct a new string value from a mix of constants, variables, literals and expressions by including their value inside a string literal
let hourlyRate = 60.0
let hoursPerDay = 8.0
let daysInWeek = 5
let weeksInYear = 52
let salaryMessage = "A person working \(hoursPerDay) hours per day for \(daysInWeek) days a week for \(weeksInYear) weeks will earn \( hourlyRate * hoursPerDay * Double(daysInWeek) * Double(weeksInYear)) in a year"
print (salaryMessage) //A person working 8.0 hours per day for 5 days a week for 52 weeks will earn 124800.0 in a year
Swift Unicode
/*
Swift's native string type is built from unicode scalar values. A unicode scalar is a unique 21 bit number for a number or character
Special Characters
\0 null character
\\ backslash
\t horizontal tab
\n line feed
\r carriage return
\" (double quote)
\' single quote
*/
let dollarSign = "\u{24}"
print(dollarSign) //$
Swift Graphme Clusters
/*
An extended graphme cluster is a sequence of one or more Unicode scalars which when combined produces a single human -readable character
//TBD
//PROVIDE SAMPLE CODE
*/
Swift Counting Characters
let swiftMessageString = "Hello World ! This is Swift 2.0 and this is better than Swift 1.2!" print("the number of characters in Swift Message String is \(swiftMessageString.characters.count)") //the number of characters in Swift Message String is 66 print (swiftMessageString.startIndex) //0 print (swiftMessageString.endIndex) //66
Swift Accessing and Modifying a String
/* Each string has an associated index type. String.Index corresponds to the position of each Character in the string */ let welcomeMessage = "Hello World !" print(welcomeMessage.capitalizedString) //Hello World ! print(welcomeMessage.characters) //CharacterView(_core: Swift._StringCore(_baseAddress: 0x00000001000080ac, _countAndFlags: 13, _owner: nil)) print(welcomeMessage.characters.count) //13 print(welcomeMessage.componentsSeparatedByString(" ")) //["Hello", "World", "!"] print(welcomeMessage.containsString("World")) //true print(welcomeMessage.decomposedStringWithCanonicalMapping) //Hello World ! print(welcomeMessage.startIndex) //0 print(welcomeMessage.endIndex) //13 print(welcomeMessage.hashValue) //4799450059838842187 print(welcomeMessage.hasPrefix("Hello")) //true print(welcomeMessage.hasSuffix("!")) //true print(welcomeMessage.localizedCapitalizedString) //Hello World ! print(welcomeMessage.localizedLowercaseString) //hello world ! print(welcomeMessage.localizedUppercaseString) //HELLO WORLD ! print(welcomeMessage.lowercaseString) //hello world ! print(welcomeMessage.rangeOfString("ell")) //Optional(Range(1..<4)) print(welcomeMessage.stringByAppendingString("This is Swift 2.0")) //Hello World !This is Swift 2.0 print(welcomeMessage.endIndex.predecessor()) // 12 //print(welcomeMessage.endIndex.successor()) // This will give a run time exception print(welcomeMessage.startIndex.successor()) // 1 //print(welcomeMessage.startIndex.predecessor()) //This will give a run time exception for index in welcomeMessage.characters.indices{ //print("index is \(index) and character is \(welcomeMessage[index])", terminator:"") print("index is \(index) and character is \(welcomeMessage[index])") } /* index is 0 and character is H index is 1 and character is e ... index is 11 and character is index is 12 and character is ! */
Swift Insert and Remove character/ characters from a string
var welcomeString = "Hello" welcomeString.insert("!", atIndex: welcomeString.endIndex) print(welcomeString) //Hello! welcomeString.insertContentsOf(" There".characters, at: welcomeString.endIndex) print(welcomeString) //Hello! There let range = welcomeString.rangeOfString(" There") print(range) //Optional(Range(6..<12)) welcomeString.removeRange(range!) print(welcomeString) //Hello!
Swift String Comparison
- String & Character Equality
- Prefix Equality
- Suffix Equality
func stringMethod4(){ let message1 = "Hello World" let message2 = "Hello World" if (message1 == message2){ print ("Both the strings are equal") } else{ print ("They are not equal") } //prints - Both the strings are equal if message1.uppercaseString != message2 { print("not same") } else{ print("same") } //Prints not same let message3 = "Sir Arthur Conan Doyle was a British writer and physician" print(message3.hasPrefix("Sir")) //true print(message3.hasPrefix("sir")) //false print(message3.hasSuffix("physician")) //true }
Unicode Representation of Strings
//TBD
//PROVIDE SAMPLE CODE
Clearly explained