Learn Swift--expand

Source: Internet
Author: User

Outreach (Extension)

an extension is the addition of new functionality to an existing class, struct, enumeration type, or protocol 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.) )

Swift's expansion can:
    • Adding computed and computed 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

Note: Extensions can add new functionality to a type, but cannot override existing functionality.

Basic syntax:
Class SomeClass {}extension SomeClass {    ///Here you can add new features for SomeClass}

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

Protocol Someprotocol {    }class someclass {}extension someclass:someprotocol {    }

Computed Properties

An extension can add a computed instance property and a computed Type property to an existing type.

Note: Extensions can add new calculated properties, but you cannot add storage properties or Add property observers to existing properties .

Extension Double {    var km:double {return self * 1_000.0}    var m:double {return self}    var cm:double {ret  Urn self/100.0}    var mm:double {return self/1_000.0}    var ft:double {return self/3.28084}}let oneinch = 25.4.mmprint (Oneinch)//0.0254let Threefeet = 3.0.ftprint (threefeet)//0.914399970739201let Amarathon = 42.0.km + 195.0. Mprint (Amarathon)//42195

Constructors

An 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 a new specified constructor or destructor to a class . Specifies that constructors and destructors must always be provided by the original class implementation.

Note: If you use an extension to add a constructor to a value type where the value type has provided default values to all storage properties, and no custom constructors are defined, you can call the default constructor and the member constructor one by one in the extension constructor of the value type. 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.

struct Size {    var width = 0.0, height = 0.0}struct point {    var x = 0.0, y = 0.0}struct rect {    //rect struct body for all properties Default values, and there is no custom constructor, so you can call the Rect-by-constructor and default constructor in the extension    var origin = point (), size = size ()}extension Rect {    //  Custom constructor init in expansion    (Center:point, size:size) {let        x = center.x-size.width/2 let        y = center.y-size.height /2        Self.init (Origin:point (x:x, y:y), size:size)    }}let rect = rect (Center:point (x:50, y:50), Size:size (w Idth:25, height:30))

Method

Extensions can add new instance methods and type methods to existing types.

Extension Int {    func repetitions (Task: ()) {for _ in        0: < self {            task ()        }    }}3.repetitions {     print ("Hello")  //print 3 times  "Hello"}

Modifying instance methods

An instance method that is added by extension can also modify the instance itself . a method that modifies or its properties in a struct and enumeration type self must label mutating The instance method as if it were modified from the original implementation.

Extension INT {    //defines a method for modifying an instance of a value type    mutating func square () {Self        = self * Self}}var number    = 3number.sq Uare ()     //number now has a value of 9

Subscript

An extension can add a new subscript to an existing type.

extension int {    subscript (var index:int), int {        var decimalbase = 1 while        index > 0 {            decimalbas  E *=            Index-= 1        }        return self/decimalbase%    }}15699632[2]     //return 615699632[3]     //return 915699632[4]/     /return 915699632[5]     //return 615699632[6]     //Return 5

Nested Types

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

Extension Int {    enum Kind {case        negative, Zero, Positive    }        var kind:kind {        switch self {case        0:            return. Zero case let number        where number > 0:            return. Positive        Default:            return. Negative        }    }}func printintegerkinds (numbers: [Int]) {for number in    numbers {        switch number.kind { C15/>case. Negative:            Print ("-") case        . Zero:            print ("0")        default:            print ("+")        }    }}printintegerkinds ([0, 11,-4, 5, 0])

Learn Swift--expand

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.