Original blog, reproduced please indicate the source
Http://blog.csdn.net/column/details/swift-hwc.html
I. Definition of extension (extensions)
An extension is the addition of new functionality to an existing class, struct, or enumeration. The extension does not need to obtain the source code of the original class.
The extension is similar to the categories in Objective C
Extensions can add features that include
1. Calculating properties and calculating static properties (you can not add storage properties and attribute observation periods)
2. New instance method and type method
3. Provide a new constructor
4. Define the following table specimen
5. Define and use new nested types
6. Make an existing type conform to an agreement
Grammar
Declared by keyword extension
Extension SomeType {//}
Extend it to conform to a protocol
Extension Sometype:someprotocol, Anotherproctocol {//protocol implementation write here}
This part of the agreement will be followed up.
Second, an example of an extended string
Students who do not understand string refer to this article I wrote earlier
http://blog.csdn.net/hello_hwc/article/details/39853023
An example covers common extensions beyond Protocol
Extension string {//Extended subscript script subscript (r:range<int>), string {get {let Substar t = Advance (Self.startindex, R.startindex, self.endindex) Let SubEnd = Advance (Substart, R.endindex-r.starti Ndex, Self.endindex) return Self.substringwithrange (Range (Start:substart, End:subend)}} Extended instance method func substring (#from: Int), String {Let end = countelements (self) return self[from. . <end]} func substring (#from: Int, Length:int), String {let end = from + length ret Urn Self[from. <end]} func substring (#from: Int, To:int)->string {return self[from. <to]}//define New constructor init (first:string,second:string) {self.init (First+second)}//define a new nested type, where the A nested type is an enumeration//so-called nested type, simple to understand is to define another type in one type enum kind{case ISINTSTR,NOTINTSTR}//Define a new instance variable, return whether this string is convertible as int var kind:kind{var result:kind = Kind.isintstr if Self.toint ()? = = nil{result =. NOTINTSTR} return result}} var str = String (first: "Hello", Second: "HWC") var str1 = str.substring (from:6 )//hwcvar str2 = str.substring (from:0,to:5)//hellovar STR3 = str.substring (from:0,length:5)//hellovar STR4 = str[0...5 ]//hellovar strkind = str.kind//notintstrif Strkind = = string.kind.notintstr{println ("not a int String")}
Note: Students who want to see the results will be able to copy this code to Palyground to see the results.
Swift Getting Started Tutorial tutorial 15-Extension (extension)