You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
letquotation="""The White Rabbit put on his spectacles. "Where shall I begin,please your Majesty?" he asked."Begin at the beginning," the King said gravely, "and go ontill you come to the end; then stop.""""
letsingleLineString="These are the same."letmultilineString="""These are the same."""
letsoftWrappedQuotation="""The White Rabbit put on his spectacles. "Where shall I begin, \please your Majesty?" he asked."Begin at the beginning," the King said gravely, "and go on \till you come to the end; then stop.""""
letlineBreaks="""This string starts with a line break.It also ends with a line break."""
Special Characters in String Literals
letwiseWords="\"Imagination is more important than knowledge\" - Einstein"
// "Imagination is more important than knowledge" - Einstein
letdollarSign="\u{24}" // $, Unicode scalar U+0024
letblackHeart="\u{2665}" // ♥, Unicode scalar U+2665
letsparklingHeart="\u{1F496}" // 💖, Unicode scalar U+1F496
letthreeDoubleQuotationMarks="""Escaping the first quotation mark \"""Escaping all three quotation marks \"\"\""""
Extended String Delimiters
letthreeMoreDoubleQuotationMarks=#"""Here are three more double quotes: """"""#
Initializing an Empty String
varemptyString="" // empty string literal
varanotherEmptyString=String() // initializer syntax
// these two strings are both empty, and are equivalent to each other
if emptyString.isEmpty {print("Nothing to see here")}
// Prints "Nothing to see here"
String Mutability
varvariableString="Horse"
variableString +=" and carriage"
// variableString is now "Horse and carriage"
letconstantString="Highlander"
constantString +=" and another Highlander"
// this reports a compile-time error - a constant string cannot be modified
Strings Are Value Types
Working with Characters
forcharacterin"Dog!🐶"{print(character)}
// D
// o
// g
// !
// 🐶
letexclamationMark:Character="!"
letcatCharacters:[Character]=["C","a","t","!","🐱"]letcatString=String(catCharacters)print(catString)
// Prints "Cat!🐱"
varinstruction="look over"
instruction += string2
// instruction now equals "look over there"
letexclamationMark:Character="!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"
letbadStart="""onetwo"""letend="""three"""print(badStart + end)
// Prints two lines:
// one
// twothree
letgoodStart="""onetwo"""print(goodStart + end)
// Prints three lines:
// one
// two
// three
String Interpolation
letmultiplier=3letmessage="\(multiplier) times 2.5 is \(Double(multiplier)*2.5)"
// message is "3 times 2.5 is 7.5"
print(#"Write an interpolated string in Swift using \(multiplier)."#)
// Prints "Write an interpolated string in Swift using \(multiplier)."
print(#"6 times 7 is \#(6*7)."#)
// Prints "6 times 7 is 42."
Unicode
Unicode Scalar Values
Extended Grapheme Clusters
leteAcute:Character="\u{E9}" // é
letcombinedEAcute:Character="\u{65}\u{301}" // e followed by ́
// eAcute is é, combinedEAcute is é
letprecomposed:Character="\u{D55C}" // 한
letdecomposed:Character="\u{1112}\u{1161}\u{11AB}" // ᄒ, ᅡ, ᆫ
// precomposed is 한, decomposed is 한
letenclosedEAcute:Character="\u{E9}\u{20DD}"
// enclosedEAcute is é⃝
letregionalIndicatorForUS:Character="\u{1F1FA}\u{1F1F8}"
// regionalIndicatorForUS is 🇺🇸
Counting Characters
letunusualMenagerie="Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"print("unusualMenagerie has \(unusualMenagerie.count) characters")
// Prints "unusualMenagerie has 40 characters"
varword="cafe"print("the number of characters in \(word) is \(word.count)")
// Prints "the number of characters in cafe is 4"
word +="\u{301}" // COMBINING ACUTE ACCENT, U+0301
print("the number of characters in \(word) is \(word.count)")
// Prints "the number of characters in café is 4"
Accessing and Modifying a String
String Indices
letgreeting="Guten Tag!"greeting[greeting.startIndex]
// G
greeting[greeting.index(before: greeting.endIndex)]
// !
greeting[greeting.index(after: greeting.startIndex)]
// u
letindex= greeting.index(greeting.startIndex, offsetBy:7)greeting[index]
// a
forindexin greeting.indices {print("\(greeting[index])", terminator:"")}
// Prints "G u t e n T a g ! "
Inserting and Removing
varwelcome="hello"
welcome.insert("!", at: welcome.endIndex)
// welcome now equals "hello!"
welcome.insert(contentsOf:" there", at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there!"
welcome.remove(at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there"
letrange= welcome.index(welcome.endIndex, offsetBy:-6)..<welcome.endIndex
welcome.removeSubrange(range)
// welcome now equals "hello"
Substrings
letgreeting="Hello, world!"letindex= greeting.firstIndex(of:",")?? greeting.endIndex
letbeginning=greeting[..<index]
// beginning is "Hello"
// Convert the result to a String for long-term storage.
letnewString=String(beginning)
Comparing Strings
String and Character Equality
letquotation="We're a lot alike, you and I."letsameQuotation="We're a lot alike, you and I."if quotation == sameQuotation {print("These two strings are considered equal")}
// Prints "These two strings are considered equal"
// "Voulez-vous un café?" using LATIN SMALL LETTER E WITH ACUTE
leteAcuteQuestion="Voulez-vous un caf\u{E9}?"
// "Voulez-vous un café?" using LATIN SMALL LETTER E and COMBINING ACUTE ACCENT
letcombinedEAcuteQuestion="Voulez-vous un caf\u{65}\u{301}?"if eAcuteQuestion == combinedEAcuteQuestion {print("These two strings are considered equal")}
// Prints "These two strings are considered equal"
letlatinCapitalLetterA:Character="\u{41}"letcyrillicCapitalLetterA:Character="\u{0410}"if latinCapitalLetterA != cyrillicCapitalLetterA {print("These two characters are not equivalent.")}
// Prints "These two characters are not equivalent."
Prefix and Suffix Equality
letromeoAndJuliet=["Act 1 Scene 1: Verona, A public place","Act 1 Scene 2: Capulet's mansion","Act 1 Scene 3: A room in Capulet's mansion","Act 1 Scene 4: A street outside Capulet's mansion","Act 1 Scene 5: The Great Hall in Capulet's mansion","Act 2 Scene 1: Outside Capulet's mansion","Act 2 Scene 2: Capulet's orchard","Act 2 Scene 3: Outside Friar Lawrence's cell","Act 2 Scene 4: A street in Verona","Act 2 Scene 5: Capulet's mansion","Act 2 Scene 6: Friar Lawrence's cell"]
varact1SceneCount=0forscenein romeoAndJuliet {if scene.hasPrefix("Act 1 "){
act1SceneCount +=1}}print("There are \(act1SceneCount) scenes in Act 1")
// Prints "There are 5 scenes in Act 1"