Swift Learning Note Five

Source: Internet
Author: User
Tags scalar

Base operator

Most of Swift's operators are the same as C and OC, and are divided into two yuan, which only records some of the nature or wording of Swift.

Assignment operator (=)

When the right side of the equals sign is a tuple with multiple values, its member values can be decomposed and assigned to constants or variables, respectively:

Let (x, y) = (12)//  x are equal to 1, and y are equal to 2

Unlike C, OC, the assignment operator itself does not return a value, so the following is an incorrect notation:

if x = y {    // This isn't valid, because x = y does not return a value}

This is primarily to prevent it from being confused with the equality operator.

Fetch remainder operator (%)

The take-rest operation is also called modulo in some languages, but it cannot be said in Swift, because the remainder is also signed when negative numbers, such as 9 4 = 1, and the second operand is ignored, that is,

A% B and a%-B always return the same value.

Unlike the take-out operator in C and OC, the take-up in Swift can also be used for floating-point numbers: 8 2.5 = 0.5

Compound assignment operator

For example, a+=2 means a=a+2, but the compound assignment operator itself does not return a value, so let B = a + = 2 is wrong.

Nil merge operator

Nil merge operator (a??). b) Expand a when optional a has value, and return the value of B if a has no value. A must be a optional value, and the values stored by B and a should be of uniform type. It's meant to be

(A! = nil)? A! : b//Here's the second one! is used to force the expansion of the optional value.

The nil merge operator is an elegant notation and is more readable, and if a has a value, then B will not participate in the operation.

Range operator

Swift has two range operators, "..." and ". < ", a...b represents the range from A to B and contains a and B, a. <b represents a to B but not a range of B, and if a=b, the range is empty, and of course, both require a cannot be greater than B.

Strings and characters

Swift's string and character syntax is simple, you can concatenate multiple strings directly with the + sign, and Swift's string provides a fast, Unicode-compliant text Processing tool.

Also, you can insert constants, variables, literals, and expressions in a string.

Swift's string type is the same as the NSString in the foundation framework, and if it is developed based on the Cocoa Foundation framework, all NSString APIs can be used on Swift's string.

string literal

string literals are defined sequences of characters enclosed in double quotation marks. For example:let somestring = "Some string literal value". At this point the compiler will drop the somestring type set to string because it is initialized with a string literal.

String literals can contain some special escape symbols:

(null), \ \ (backslash), \ t (horizontal tab), \ n (line break), \ r (carriage return), \ "(double quotation mark) and \" (single quote)

You can also include direct Unicode-scalar characters (Unicode, Unicode), which refers to any Unicode code point within a specified range, which represents a Unicode character. When you include a Unicode scalar in a string, start with u, plus the code point number surrounded by curly braces.

Let Wisewords ="\ "Imagination is more important than knowledge\"-Einstein"//"Imagination is more important than knowledge"-EinsteinLet dollarsign ="\u{24}"        //$, Unicode scalar u+0024Let Blackheart ="\u{2665}"      //♥, Unicode scalar u+2665Let Sparklingheart ="\u{1f496}" //??, Unicode scalar u+1f496

Creates a string that can be created with a string literal or with the initialization method: string ().

Unlike OC, a string in Swift can be modified if it is assigned to a variable. OC, you need to select NSString and nsmutablestring two classes to determine if the string can be modified.

In Swift, a string is a value type (value type), and when it is assigned to a constant or variable, or is passed to a function, its value is copied out for assignment and delivery, not the original one. This is not the same as OC, in OC You create an instance of NSString, and you are assigning and passing a reference to that nsstring. No copy operation has occurred.

The reason why Swift is changing this is to reduce the difficulty of the developer, for example, when your method receives a string, you can be sure that the string is completely under your control, without worrying about modifying it elsewhere because it is not a reference, but a copy of the value. But the compiler doesn't actually copy the value every time, it just does this when it's needed, which can reduce performance overhead.

Character

A string is a set of character sets arranged in an ordered column. You can iterate through the characters in a for-in string.

 for inch " Dog!?? " {    println (character)}//  D//  o//  G//  ! //  ??

A string can also be created by a character array:

Let catcharacters: [Character] = ["C""a""t " " ! " " ?? "  = String (catcharacters) println (catstring)//  prints "Cat!??"

Note: You cannot append a string or character (append) to an already defined character type variable (Character), because the character type is a single character.

string interpolation (string interpolation)

Swift's string can be mixed into a lot of other things such as constants, variables, expressions, literals, and so on, with backslashes and parentheses to achieve this kind of insertion, this feature is very useful.

3"\ (multiplier) times 2.5 is \ (Double (multiplier) * 2.5)"//  Message is ' 3 times 2.5 is 7.5 '

Note: Expressions inside parentheses cannot contain non-escaped double quotes, backslashes, or carriage returns or line feeds.

Extended character clusters (Extended grapheme Clusters)

Grapheme refers to the smallest unit in a natural language, which does not necessarily have a practical meaning, but combines them into a single character of the language. Each character (Character) of the Swift language is a separate extended character family, and an extended character cluster is an ordered arrangement of one or more Unicode scalar (Unicode-pure quantities) to be combined into a readable character.

For example, the letter E can be a single Unicode scalar:u+00e9, or it can be a combination of more than one pure quantity: u+0065u+0301 (where u+0065 is the alpha). In Swift, both cases are considered to be a character, so when getting the string length (with the global Function count ()), the returned value is the same, which means that the change in the string does not necessarily mean that its length has changed.

Note the difference between this and the length of nsstring in OC, NSString is based on the number of 16-bit cells that are contained in the string when the UTF-16 is encoded, rather than the numbers of Unicode extended character clusters. To reflect this distinction, the length property of NSString is replaced by the Utf16count function in Swift.

The API for strings

Each string has an associated index type (index type) that identifies the position of the character in the string, and uses the specific index to get the character at that position in a string. startindex and Endindex return the initial and end positions of the string.

The value of an indexed type of string can be obtained either by predecessor () or successor () the index value that precedes or follows it. Any index value can be obtained through a sequence of other index values, or through a global function advance (start:n:), attempting to get an index outside the range of string triggers a run-time error.

Let greeting ="Guten Tag"//Prints "greeting:string =" Guten Tag ""println (Greeting.startindex)//0println (Greeting.endindex)//9greeting[greeting.startindex.successor ()]//ugreeting[greeting.endindex.predecessor ()]//gLet index = advance (Greeting.startindex,7) Greeting[index]//aGreeting.endIndex.successor ()//fatal Error:can not increment endIndex

Indicies (_:) can create an index range for all individual characters in a string

 for inch Indices (greeting) {    print ("")}//  prints "G u t e n   T A G "

Insert (_:atindex:) inserts a character into a string-specific index position:

" Hello " Welcome.insert ("! " , AtIndex:welcome.endIndex) println (Welcome)//  prints "hello!"

Splice (_:atindex:) is used to insert a string into a string at a specific index location:

Welcome.splice ("  there", AtIndex:welcome.endIndex.predecessor ()) println (Welcome)  //  prints "Hello there!"

Removeatindex (_:) is used to delete a character at a specific index position of a string:

Welcome.removeatindex (Welcome.endIndex.predecessor ()) //  ! println (Welcome) // Prints "Hello there"

RemoveRange (_:) to delete substrings of a specific range of strings:

Let range = Advance (Welcome.endindex,-6). <welcome.endIndexwelcome.removeRange (range) println (welcome)//  prints "Hello"

String comparisons are made directly with = = and! =.

When the extended character clusters of the strings are equal (canonically) (canonically equality means that they have the same linguistic meaning and appearance, regardless of their Unicode pure amount), they are judged to be equal.

//"voulez-vous un café?" using LATIN SMALL letter E with ACUTELet eacutequestion ="voulez-vous un caf\u{e9}?" //"voulez-vous un café?" using LATIN SMALL letter E and combining ACUTE ACCENTLet combinedeacutequestion ="voulez-vous un caf\u{65}\u{301}?" ifEacutequestion = =combinedeacutequestion {println ("these strings is considered equal")}//prints "These, strings is considered equal"

Hasprefix (_:) and Hassuffix (_:) Used to determine whether a string contains a specific prefix or suffix. They return a Boolean value.

The Unicode representation of a string

When a Unicode-encoded string is written to a text file or other store, the Unicode scalars in the string are encoded in a variety of Unicode-based encoding formats. For example, UTF-8, UTF-16, UTF-32, you can get its representation at different encodings by the properties of string:

The UTF8 property gets a set of code elements when the UTF-8 encoding format is obtained;

The Utf16 property gets a set of code elements when the UTF-16 encoding format is obtained;

The Unicodescalars property gets a set of code elements when the UTF-32 encoding format is obtained;

Let dogstring ="Dog???" forCodeUnitinchDogstring.utf8 {print ("\ (codeUnit)")}print ("\ n")//111 103 226 188 159 144 182 forCodeUnitinchdogstring.utf16 {print ("\ (codeUnit)")}print ("\ n")//111 103 8252 55357 56374 forScalarinchdogstring.unicodescalars {print ("\ (scalar.value)")}print ("\ n")//68 111 103) 8252 128054

For scalar in Dogstring.unicodescalars {
println ("\ (scalar)")
}
D
O
G
// ?
// ??

This is where the next introduction to collection types begins.

Swift Learning Note Five

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.