A string is an ordered set of characters, such as "hellow, world" or "cisteon ". The strings in Swift are composedStringType, correspondingCharacterA set of Type values.
In SwiftStringType provides a high speed and compatibility for your programmingUnicode Specification. The syntax for Swift to create and process strings is lightweight and readable, similar to the string syntax in C. Concatenation of strings is very simple. You only need to add two strings with the + operator. Whether the string value is variable depends on whether it is a constant or a variable, which is consistent with other types in Swift.
SwiftStringIn addition to concise syntax, the type is also a high-speed, modern string implementation solution. Each string is encoded independently.UnicodeEach character can contain differentUnicodeExpress access.
Swift strings also support inserting constants, variables, literal quantities, and expression values in long strings. This process is called string insertion. This makes it easier to display, store, and output custom string values.
Note:
SwiftStringType and underlying FoundationNSStringClass seamless connection. If you use the Foundation framework in Cocoa/Cocoa TouchStringIn addition to the featuresStringValue, can be calledNSStringAll APIs of the class. You can also setStringPass the value to anyNSStringInstanceAPIMethod.
MoreString and Foundation/CocoaFor more information about the framework, seeSwift's combination with Cocoa and Objective-C(This part of content is not included in this book, but is translated after it is translated ).
String Literal
In the codeStringValue embeddingString Literal(String literal). A string literal is a fixed sequence of text characters enclosed by a pair of double quotes.
A string literal can provide an initial value for a constant or variable:
let someString = "Some string literal value"
Note: Swift infers constants.SomeStringIsStringType, becauseSomeStringIs initialized by a string literal.
The string literal contains the following special characters:
·Special escape characters: \ 0 (null character), \ (backslash, should be a single slash after escape -- Joe. huang), \ t (horizontal tab), \ n (line break), \ r (carriage return), \ "(double quotation marks), and \ '(single quotation marks)
·Single-byte Unicode scalar, writing \ xNn, WhereNnReturns two hexadecimal digits.
·Double-byte Unicode scalar, writing \ uNnnn, WhereNnnnFour hexadecimal digits
·Four-byte Unicode scalar, writing \ UNnnnnnnnnn, WhereNnnnnnnnnnEight hexadecimal digits
The following code shows examples of these special characters. ConstantWiseWordsContains double quotation marks after two escape characters. ConstantDollarSign,BlackHeartAndSparklingHeartIt displays three different writing formats of Unicode scalar characters:
Let wiseWords = "\" Imagination is more important than knowledge \ "-Einstein" // "Imagination is more important than knowledge"-Einstein // output "Imagination is more important than knowledge "- einstein let dollarSign = "\ x24" // output $, unicode scalar U + 0024let blackHeart = "\ u2665" // output♥, Unicode scalar U + 2665let sparklingHeart = "\ U0001F496" // output, Unicode scalar U + 1F496
Initialize an empty string
Create a long string. The first step is to create an empty string.StringValue. You can assign a literal value to a variable or use the initialization syntax to initialize a newStringInstance:
1 var emptyString = "" // empty String literal quantity 2 var anotherEmptyString = String () // initialization syntax 3 // both String objects are null and are equivalent to each other
You can useIsEmptyWhether the value of the property check string is null:
1 if emptyString. isEmpty {2 println ("Nothing to see here") 3} 4 // output "Nothing to see"
String Variability
Whether the value of a specific String can be modified (that isVariable,Mutable), You can assign a value to a variable (which can be modified) or constant (which cannot be modified) by declaring ):
1 var variableString = "Horse" 2 variableString + = "and carriage" 3 // The value of variableString is now "Horse and carriage" 4 5 let constantString = "Highlander" 6 constantString + = "and another Highlander" 7 // compilation error-constant string value cannot be changed
Note:
This implementation scheme andObjective-C/CocoaThe string variability of is different, the latter is by either of the two classes to which the instance belongs (NSStringOrNSMutableString) To declare whether the string is variable.
String belongs to the Data Type
SwiftStringType isData transfer type(Value type). IfStringThe value is passed to a function or method, or assigned to a constant or variable.StringThe value is alsoCopy (Copied)In the past. Both of these situations areStringCreates a new copy of the value. The actual transfer or assignment is its copy, not its original Instance. For details about the data transfer type, seeBoth the structure and enumeration types are value transfer types.(Translated in later chapters ).
Note:
This behavior correspondsCocoaOfNSStringDifferent.CocoaCreateNSStringWhen an instance is passed to a function or method, or a value is assigned to a variable, the actual transfer or assignment is the sameNSStringInstanceReference(Reference, non-copy -- copy ). There will be no string copying operation in the middle, unless otherwise specified.
SwiftStringThe "Default copy" action of ensures that the function or method is passed.StringWhen the value is for you, thisStringThe value does belong to you, but it has nothing to do with its source. It is certain that the string you receive will never change unless you modify it yourself.
In the background, the Swift compiler will optimize the memory usage of the string and create a copy of the string only when absolutely required. Therefore, strings belong to the value type, so that your code can always achieve the best performance.
Character operations
In SwiftStringType is a segmentCharacterAn ordered set of values.CharacterThe value represents a Unicode character. You can useFor-inCyclically traverse each of the stringsCharacterValue:
1 for character in "Dog! "{2 println (character) // output (character) 3} 4 // D5 // o6 // g7 //! 8 //
For-inThe usage will be translated later in the process control chapter.
In additionCharacterType Description: You can create character constants or variables separately from the single-character string literal:
1 let yenSign: Character = "¥" 2 // specify yenSign as Character type -- Joe. Huang
Character statistics
You can use the global method.CountElementsTo count the number of characters in a string, and pass the string as a unique parameter:
1 let users = "Koala, Snail Il, Penguin, Dromedary" 2 println ("unusualMenagerie has \ (countElements (unusualMenagerie) characters") 3 // output "bytes has 40 characters"
Note:
Different Unicode characters and different representations of the same Unicode character occupy different storage spaces in the memory. Therefore, to calculate the length of a string, you must traverse the entire string and count each character in sequence. If you are processing long string values, remember that,CountElementsThe function must traverse each character in the string to obtain its exact number of characters.
Note that,CountElementsThe number of characters returned.LengthThe number of characters returned by the attribute is not always the same. The length of the NSString depends on the string's UTF-16 form16The number of bit code units, rather than the number of Unicode characters in the string. To differentiate this fact, in the Swift languageLengthAttribute must passStringValueUtf16countAttribute access.
Concatenation of strings and characters
StringAndCharacterValues can be added together with the addition operator (+) (that isConnection,Concatenate) To get a new String value:
Let string1 = "hello" let string2 = "there" let character1: Character = "! "Let character2: Character = "? "Let stringPlusCharacter = string1 + character1 // equals to" hello! "Let stringPlusString = string1 + string2 // equals to" hello there "let characterPlusString = character1 + string1 // equals "! Hello "let characterPlusCharacter = character1 + character2 // equals "!? "
You can also use the addition assignment operator (+ =)StringAppend at the end of the Variable)StringOrCharacterValue:
Var instruction = "look over" instruction + = string2 // instruction now equals "look over there" // instruction is now equal to "look there" var welcome = "good morning" welcome + = character1 // welcome now equals "good morning! "// Welcome is equal to" good morning! "
String insertion
String insertion is a combination of constants, variables, literal quantities, and expressions.StringValue method. Each item inserted in the string literal must be enclosed by a pair of parentheses with a front backslash:
1 let multiplier = 32 let message = "\ (multiplier) times 2.5 is \ (Double (multiplier) * 2.5) "3 // message is" 3 times 2.5 is 7.5 "4 // message is" 3 multiplied by 2.5 is 7.5"
In the above example, the constantMultiplierTo\ (Multiplier)As a placeholder to insert the string literal. The placeholder isMultiplier.
A long expression later usesMultiplier. This expression calculatesDouble (multiplier) x 2.5And the result(7.5)The string is inserted. In the above example,\ (Double (multiplier) * 2.5)Embedded as a placeholder in the string literal.
Note:
When a string is inserted, the expressions in the brackets cannot contain unescaped double quotation marks (") or backslash (\), and cannot contain carriage return or line breaks.
String comparison
Swift provides three string comparison methods: string matching, prefix matching, and suffix matching.
String Matching
If twoStringThe characters and their sequence of values are identical. The two are equal:
1 let quotation = "We're a lot alike, you and I. "2 let sameQuotation =" We're a lot alike, you and I. "3 if quotation = sameQuotation {4 println (" These two strings are considered equal ") 5} 6 // output" the two strings are equal"
Prefix/suffix matching
Check whether a string contains a specified character prefix or suffix.HasPrefixAndHasSuffixMethod. Both methods receive oneStringType parameter and return a Boolean value. The two Methods Compare the prefix/suffix strings with the basic strings one character by one character.
In the following example, there is a string array with the content of Shakespeare's play "Romeo and Juliette" (Romeo and Juliet) Locations of the first two scenes:
1 let romeoAndJuliet = [2 "Act 1 Scene 1: Verona, A public place", // Scene 1: Verona, A public place 3 "Act 1 Scene 2: capulet's mansion ", // Scene 1 Scenario 2: Capulet's home 4" Act 1 Scene 3: A room in Capulet's mansion ", // Scene 3: 5 "Act 1 Scene 4: A street outside Capulet's mansion", // scenario 4: 6 "Act 1 Scene 5" outside Capulet's home: the Great Hall in Capulet's mansion ", // Scene 5: 7" Act 2 Scene 1: Outside Capulet's mansion ", // Scene 2: Capulet's 8 "Act 2 Scene 2: Capulet's orchard", // Scene 2: Capulet's orchard 9 "Act 2 Scene 3: outside Friar Lawrence's cell ", // Scene 2 3: 10" Act 2 Scene 4: A street in Verona ", // scenario 4: 11 "Act 2 Scene 5: Capulet's mansion" on a street in Verona, // scenario 5: capulet's home 12 "Act 2 Scene 6: Friar Lawrence's cell" // Scene 6: Friar Lawrence's church 13]
PairRomeoAndJulietUse the element in the arrayHasPrefixMethod to count the number of scenes in Act 1:
1 var act1SceneCount = 02 for scene in romeoAndJuliet {3 if scene. hasPrefix ("Act 1") {4 + + act1SceneCount5} 6} 7 println ("There are \ (act1SceneCount) scenes in Act 1 ") 8 // output "Act 1 (Act 1) has five scenes"
SimilarlyHasSuffixMethod to calculate the number of times that occur in Capulet's mansion and Friar Lawrence's cell:
1 var mansionCount = 0 2 var cellCount = 0 3 for scene in romeoAndJuliet {4 if scene. hasSuffix ("Capulet's mansion") {5 ++ mansionCount 6} else if scene. hasSuffix ("Friar Lawrence's cell") {7 ++ cellCount 8} 9} 10 println ("\ (mansionCount) mansion scenes; \ (cellCount) cell scenes ") 11 // output "6 mansion and 2 cell"
Thank you, Swifter-QQ group: 362232993 ~
Fork: https://github.com/Joejo/Swift-lesson-for-chinese