iOS development Language Swift entry---extensions

Source: Internet
Author: User

iOS development language Swift Getting started serial-extensions

An extension is the addition of a new feature (functionality) to an existing class, struct, or enumeration type. This includes the ability to extend a type without having permission to get the original source code (that is, reverse modeling). Extensions are similar to classifications in Objective-c (categories). (unlike objective-c, however, Swift's extension has no name.) )
The extensions in Swift can:
Adding computed properties and calculating static properties
Defining instance methods and type methods
To provide a new constructor
Define Subscript
Defining and using a new nested type
Make an existing type conform to a protocol
Attention:
If you define an extension to add new functionality to an existing type, this new feature is available for all existing instances of that type, even if they are defined earlier in your extension.
  

Extended syntax (Extension Syntax)

Declare an extension using the keyword extension:

extension SomeType {    // 加到SomeType的新功能写到这里}

An extension can extend an existing type so that it can be adapted to one or more protocols (protocol). When this happens, the name of the protocol should be written exactly in the same way as the class or struct's name:

extension SomeType: SomeProtocol, AnotherProctocol {    // 协议实现写到这里}

The Protocol followers (Protocol conformance) added in this way are referred to as adding Protocol followers in the extension

Computed attributes (Computed properties)

An extension can add a computed instance property and a computed Type property to an existing type. The following example adds 5 computed instance properties to Swift's built-in double type, providing basic support for collaborating with distance units.

Extension Double {varkm:double {return  Self * 1_000. 0}varm:double {return  Self}varcm:double {return  Self / 100.0}varmm:double {return  Self / 1_000. 0}var ft: Double {return  Self / 3.28084}} LetOneinch= 25.4.Mmprintln ("one inch is \ (oneinch) meters")//Print out: "One inch is 0.0254 meters" LetThreefeet= 3.ftprintln"Three feet is \ (threefeet) meters")//Print output: "Three feet is 0.914399970739201 meters"

The meaning of these computed attribute representations is to treat a value of type double as a length value under a unit.  Even though they are implemented as computed properties, these properties can still be followed by a floating-point literal with dot syntax, which is precisely how distance conversions are achieved using these floating-point literals. In the above example, a double value of 1.0 is used to denote "1 meters".  This is why the M computed property returns the self--expression 1.m, which is considered to be the double value of calculation 1.0. Other units require some conversion to represent the values measured under the meter. 1-kilometer is equal to 1,000 meters, so the KM calculated attribute is to multiply the value by 1_000.00 to convert it to the value of the unit meter.  Similarly, 1 meters has 3.28024 feet, so the FT-computed attribute divides the corresponding double value by 3.28024来 to achieve the unit conversion of feet to meters. These properties are read-only computed properties, all of which are simply considered to be not represented by the GET keyword. Their return values are double and can be used for all mathematical calculations that accept a double:

let42195.mprintln("A marathon is \(aMarathon) meters long")// 打印输出:"A marathon is 42195.0 meters long"

Note: The extension can add new computed properties, but you cannot add storage properties or add property observers to an existing attribute.

Constructor (initializers)

The

Extension can add a new constructor to an existing type.  This allows you to extend other types, use your own custom type as a constructor parameter, or provide additional initialization options that are not included in the original implementation of the type. Extensions can add new convenience constructors to classes, but they cannot add new specified constructors or destructors to the class.  The specified constructor and destructor must always be provided by the original class implementation. Note: If you use an extension to add a constructor to a value type, you can call the default constructor in the extension constructor of the value type when the value type has supplied a default value to all the storage properties, and no custom initializers is defined (default  initializers) and a member constructor (memberwise initializers).  As described in the constructor proxy for value types, the above rules no longer apply if you have already written the constructor as part of the original implementation of the value type. The following example defines a custom structure rect that is used to describe a geometric rectangle. This example also defines two auxiliary struct size and point, both of which take 0.0 as the default value for all properties:

struct Size {    var0.00.0}struct Point {    var0.00.0}struct Rect {    var origin = Point()    var size = Size()}

Because the struct RECT provides default values for all its properties, as described in the default constructor, it can automatically accept a default constructor and a member-level constructor. These constructors can be used to construct a new Rect instance:

let defaultRect = Rect()let2.02.0),    5.05.0))

You can provide an additional constructor that uses a special center point and size to extend the rect struct:

extension Rect {    init(center: Point, size: Size) {        let originX = center.x - (size.width2)        let originY = center.y - (size.height2)        self.init(origin: Point(xy: originY), size: size)    }}

The new constructor first calculates a suitable origin based on the provided center and size values. Then call the struct Auto member constructor init (Origin:size, which saves the new origin and size to the appropriate attribute:

let4.04.0),    3.03.0))// centerRect的原点是 (2.5, 2.5),大小是 (3.0, 3.0)

Note: If you use extensions to provide a new constructor, you still have the responsibility to ensure that the construction process is fully initialized for all instances. Method (Methods) extension to add new instance methods and type methods to an existing type. The following example adds a new instance method named repetitions to the int type:

extension Int {    func repetitions(task: () -> ()) {        for i in 0..self {            task()        }    }}

This repetitions method uses a single ()-()-()-()-()-type parameter, which indicates that the function has no parameters and does not have a return value. After defining the extension, you can call the repetitions method on any integer, and the function is to perform a task multiple times:

3.repetitions({    println("Hello!")    })// Hello!// Hello!// Hello!

You can use trailing closures to make calls more concise:

3.repetitions{    println("Goodbye!")}// Goodbye!// Goodbye!// Goodbye!
Modify instance methods (mutating Instance Methods)

An instance method that is added by extension can also modify the instance itself.  A method that modifies self or its properties in a struct and enumeration type must label the instance method as mutating, just as the modification method from the original implementation. The following example adds a new modified method named Square to the Swift int type to implement a square calculation of the original value:

extension Int {    mutating func square() {        selfselfself    }}var3someInt.square()// someInt 现在值是 9
Subscript (subscripts)

An extension can add a new subscript to an existing type. This example adds an integer subscript to the Swift built-in type int. The subscript [n] Returns the decimal number from the right-to-left number of nth digits 123456789[0] return 123456789[1] return, etc.

extension int {subscript (digitindex:int), int {varDecimalbase =1             for_inch 1... Digitindex {decimalbase *=Ten}return(self/decimalbase)%Ten}}746381295[0]//returns 5746381295[1]//returns 9746381295[2]//returns 2746381295[8]//Returns 7

If the int value does not have enough digits, that is, the subscript is out of bounds, then the next bidding clubs of the above implementation returns 0 because it automatically complements 0 on the left side of the number:

746381295[9]//returns 0, 即等同于:0746381295[9]
Nested types (Nested Types)

Extensions can add new nested types to existing classes, structs, and enumerations:

Extension Character {enumKind { CaseVowel, consonant, other}varKind:kind {SwitchString (self). lowercasestring { Case "a","E","I","O","U":return. Vowel Case "B","C","D","F","G","H","J","K","L","M","n","P","Q","R","S","T","V","W","x","Y","Z":return. Consonantdefault:return. Other}}}

This example adds a new nested enumeration to character. The enumeration named kind represents the type of a particular character.  Specifically, it means that the characters in a standard Latin script are vowels or consonants (regardless of spoken and local variants), or other types.  This example also adds a new compute instance property to character, kind, to return the appropriate kind enumeration member. Now, this nested enumeration can be used in conjunction with a character value:

Func Printletterkinds (Word: String) {println ("' (word) ' is made up of the following kinds of letters:") forCharacterinchWord {SwitchCharacter.kind { Case.Vowel:Print("Vowel") Case.consonant:Print("consonant") Case. Other:Print("Other")        }    }Print("\ n")}printletterkinds ("Hello")// ' Hello '  isMade up ofThe following kinds of Letters://Consonant vowel consonant consonant vowel

The input to the function printletterkinds is a string value and iterates over its characters. During each iteration, consider the kind computed property of the current character and print out the appropriate category description.  So printletterkinds can be used to print the type of all letters in a complete word, as shown in the word "hello" above. Note: Since the known character.kind is a character.kind type, all member values in Character.kind can be abbreviated in the form of a switch statement, such as use. Vowel instead of character.kind

iOS development Language Swift entry---extensions

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.