Swift getting started tutorial 15-extension)

Source: Internet
Author: User

Swift getting started tutorial 15-extension)
 

1. extensions Definition
Extension is to add new functions 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.
Extended functions include

1. Calculation attributes and calculation static attributes (you cannot add storage attributes and attribute observation periods)
2. New instance method and type Method
3. Provide a new Constructor
4. Define the following table specimens
5. Define and use new nested types
6. Make existing types conform to a protocol

Syntax
Declared by the keyword extension

extension SomeType {// }
Scale to make it conform to a protocol
Extension SomeType: SomeProtocol, AnotherProctocol {// protocol implementation written here}
This part of the agreement will be explained later


Ii. extended String instance
If you are not familiar with String, refer to the article I wrote earlier.
Http://blog.csdn.net/hello_hwc/article/details/39853023
One example covers common extensions besides protocols
Extension String {// extended subscript script subscript (r: Range
 
  
)-> String {get {let subStart = advance (self. startIndex, r. startIndex, self. endIndex) let subEnd = advance (subStart, r. endIndex-r. startIndex, 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 ..
  
   
String {let end = from + length return self [from ..
   
    
String {return self [from ..
    
     
Note: If you want to see the result, copy the code to palyground to see the result.
    
   
  
 

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.