Introduction to Swift (12)--using extension to add an inverse output string method

Source: Internet
Author: User
Tags scalar

Swift does not seem to have a way to output strings in reverse order, and then decides to add a reverse method to the String class by extension (Extension) to reverse the output string.

First create a swift file, the naming rules are not very clear, so for a moment to imitate OC called String+operation Bar, and then realize we need to expand the method. Let's put the code on it and then explain the code.

//string+operation.swifftImportFoundation//Reverse output of strings in SwiftExtensionString{func Reverse () -String{varReturnstring:String = ""for (varI=Count Self)- 1; I>= 0;--i) {returnstring.Append Self[Advance Self.StartIndex, I)])} return returnstring}}

Because of the string in swift, which is a collection of extensible alphabet sets, Apple does not recommend that we operate directly with an integer subscript, as this may insert data into a Unicode scalar that would otherwise be a complete word.

Different characters can require Different amounts of memory to store, so in order to determine which Character are at a PA Rticular position, you must iterate the all Unicode scalar from the start or end of this String. For this reason, Swift strings cannot is indexed by integer values.

So if you want to traverse a string, you can use the index of string to handle it. First look at the source code:

struct Index : BidirectionalIndexType, Comparable, Reflectable {        func successor() -> String.Index        func predecessor() -> String.Index        func getMirror() -> MirrorType    (i: String.Index) -> Character { get }

It can be found that the string defines a subordinate script, the passed parameter is a variable of type String.index, and this index is the struct body defined in swift, there are methods such as successor and predecessor.

The first parameter of the advance method represents the offset of the second parameter, actually index. Pass

self[advance(self.startIndex, i)]

This code actually uses the subscript to iterate through the string, taking out the elements of the character type, as long as the Append method is called.

The use of expansion (Extension) is also simple:

varString"hello world"println(s.Reverse())// 输出结果是 dlrow olleh

It is also possible to use index completely without the subscript, for example, the following code can traverse a string in sequence:

for (varindexselfindexselfindexindex.successor()){    returnString.append(self[index])}

However, this is not a good way to traverse strings backwards, because you can see that Self[self.startindex] reads the first character of the string, but cannot use self[self.endindex], otherwise it will have an out-of-bounds error. So if you try to traverse strings in reverse order in this way, it can be tricky. It is recommended to use the first type.

See the full column-"Swift easy Getting Started"

"Introduction to Swift (i)--basic syntax"
"Introduction to Swift (ii)--character and string"
"Introduction to Swift (iii)--tuples (tuple)"
"Introduction to Swift (iv)--optional type (optionals) and assert (Assert)"
"Getting Started with Swift (v)--Arrays (array)"
"Introduction to Swift (vi)--Dictionary (Dictionary)"
"Introduction to Swift (vii)-structure (struct)"
"Introduction to Swift (eight)--powerful redundancy operator"
"Introduction to Swift (ix)--string and int, Double, float and other numbers convert each other"
"Introduction to Swift (10)-circular reference, weak reference, and no master reference"
"Introduction to Swift (11)--type conversion with IS, as Operation"
"Introduction to Swift (12)--using extension to add an inverse output string method"

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Introduction to Swift (12)--using extension to add an inverse output string method

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.