Some basic extensions of extension are used in Swift to explain _swift

Source: Internet
Author: User
Tags diff instance method mixed mul type casting

The functionality of an existing class, struct, or enum type can be added with the help of an extension. The functionality of a type can be joined with an extension, but the overridden feature cannot use the extension.

Swift Extended functionality:

    • To add a calculated property and evaluate the Type property
    • Ways to define instances and types
    • Provides a new initialization
    • Define Subscript
    • Defining and using new nested types
    • To make an existing type conform to the protocol

Extensions with keyword Extension declaration

Grammar

Copy Code code as follows:

Extension SomeType {
New functionality can be added here
}
An existing type can also be joined with an extension to make it a protocol standard and its syntax is similar to a class or struct.

Extension Sometype:someprotocol, Anotherprotocol {
Protocol requirements is described here
}




Calculation Properties
The calculation of the instance and type properties can also be extended with the help of the extension implementation.


Copy Code code as follows:

Extension Int {
var Add:int {return self + 100}
var sub:int {return self-10}
var mul:int {return self * 10}
var div:int {return SELF/5}
}

let addition = 3.add
println ("Addition is \ (addition)")

Let subtraction = 120.sub
println ("Subtraction is \ (subtraction)")

Let multiplication = 39.mul
println ("multiplication is \ (multiplication)")

Let Division = 55.div
println ("Division is \ (Division)")

Let mix = 30.add + 34.sub
println ("Mixed Type is \ \ Mix")




When we use playground to run the above program, we get the following results.

Addition is the
subtraction is a
multiplication is 390 division is one
Mixed Type is 154

Initialization device
Swift can flexibly add to existing types by extending new initialization. Users can add their own custom types to extend defined types, and additional initialization options are possible. The extension only supports Init (). and Deinit () is not supported by extension.

Copy Code code as follows:



struct SUM {


var num1 = num2 = 200


}





struct diff {


var no1 = NO2 = 100


}





struct Mult {


var a = SUM ()


var b = diff ()


}





Let Calc = mult ()


println ("Inside mult block \ (CALC.A.NUM1, calc.a.num2)")


println ("Inside mult block \ (calc.b.no1, Calc.b.no2)")





Let Memcalc = Mult (A:sum (num1:300, num2:500), B:diff (no1:300, no2:100))





println ("Inside mult block \ (MEMCALC.A.NUM1, memcalc.a.num2)")


println ("Inside mult block \ (memcalc.b.no1, Memcalc.b.no2)")





Extension Mult {


Init (X:sum, Y:diff) {


Let X = X.num1 + x.num2


Let Y = Y.no1 + Y.no2


}


}


Let a = SUM (num1:100, num2:200)
println ("Inside Sum block:\ (a.num1, a.num2)")


Let B = diff (no1:200, no2:100)
println ("Inside Diff block: \ (b.no1, B.no2)")




When we use playground to run the above program, we get the following results.

Inside mult Block (a) Inside mult block ($) Inside mult block (
300) Inside mult
Inside Sum block: (MB)
Inside Diff Block: (200, 100)

Method
new instance methods and types of methods that can be further added to subclasses with the help of extensions.

Copy Code code as follows:

Extension Int {
Func Topics (summation: ()-> ()) {
For _ in 0..<self {
Summation ()
}
}
}

4.topics ({
println ("Inside Extensions block")
})

3.topics ({
println ("Inside Type casting Block")
})




When we use playground to run the above program, we get the following results.

Inside Extensions block Inside Extensions blocks Inside Extensions block Inside
Extensions block
Inside Type casting block
Inside type casting blocks
Inside type casting block

The topics () function uses the type of the argument (summation: ()-> ()) to indicate that the function takes no arguments and that it does not return any values. The function is called multiple times, the block is initialized, and the topic () method is initialized.

Variant of different instance methods
An instance method can also be a variant of an extension declaration.

modifying its own structure and counting methods or its attributes must mark instance method variants, as if from a primitive method of implementing deformation.

Copy Code code as follows:

Extension Double {
Mutating Func Square () {
Let pi = 3.1415
Self = pi * self * self
}
}

var Trial1 = 3.3
Trial1.square ()
println ("Area of Circle is: \ (Trial1)")


var Trial2 = 5.8
Trial2.square ()
println ("Area of Circle is: \ (Trial2)")


var Trial3 = 120.3
Trial3.square ()
println ("Area of Circle is: \ (TRIAL3)")




When we use playground to run the above program, we get the following results.

Area of Circle is:34.210935 area of
Circle is:105.68006 area of
Circle is:45464.070735

Subscript
Adding a new label has declared an instance can also be extended.

Copy Code code as follows:

Extension Int {
Subscript (var multtable:int)-> Int {
var no1 = 1
While multtable > 0 {
No1 *= 10
--multtable
}
Return (SELF/NO1)% 10
}
}

println (12[0])
println (7869[1])
println (786543[2])



When we use playground to run the above program, we get the following results.

2
6
5

Nested types
nested types are classes, structs, and enumeration instances, and can also be extended with the help of an extension.

Copy Code code as follows:



Extension Int {


Enum Calc


{


Case add


Case Sub


Case Mult


Case Div


Case anything


}

   var print:calc {
      switch self
      {
         case 0:
             return. Add
         Case 1:
             return. Sub
         Case 2:
            return. Mult
          Case 3:
            return. DIV
         Default:
             return. Anything
      }
  }
}

Func result (numb: [Int]) {
For I in numb {
Switch I.print {
case. Add:
println ("10")
Case. Sub:
println ("20")
Case. Mult:
println ("30")
case. Div:
println ("40")
Default
println ("50")

}
}
}

Result ([0, 1, 2, 3, 4, 7])




When we use playground to run the above program, we get the following results.

 
50 m 

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.