Swift Chinese tutorial (7)-protocol, extension, and generic

Source: Internet
Author: User

Protocols and Extensions Protocols (interfaces) and Extensions

Swift uses the Keyword protocol to declare a protocol (Interface ):

Both class (classes), enumeration (enumerations), and structure (structs) can adopt the protocol (protocol ):

 1 class SimpleClass: ExampleProtocol { 2     var simpleDescription: String = "A very simple class." 3     var anotherProperty: Int = 69105 4     func adjust() { 5         simpleDescription += "  Now 100% adjusted." 6     } 7 } 8 var a = SimpleClass() 9 a.adjust()10 let aDescription = a.simpleDescription11  12 struct SimpleStructure: ExampleProtocol {13     var simpleDescription: String = "A simple structure"14     mutating func adjust() {15         simpleDescription += " (adjusted)"16     }17 }18 var b = SimpleStructure()19 b.adjust()20 let bDescription = b.simpleDescription

Exercise:

Add an enumeration to implement this interface as shown in the preceding example.

Note that in the above example, the mutating keyword is used to declare a method adjust to change the SimpleStructure structure, while the SimpleClass class does not use the mutating keyword, because the method in the class can change the class at any time. (To put it bluntly, the methods in the structure should be marked with the mutating keyword to change the structure. This practice will be addressed in the subsequent translation of methods)

Swift uses the extension keyword to provide existing type extension functions. For example, if a new method or attribute is added, you can add a protocol (Interface) for the type declared elsewhere ), even the referenced library or framework:

1 extension Int: ExampleProtocol {2     var simpleDescription: String {3     return "The number \(self)"4     }5     mutating func adjust() {6         self += 427     }8 }9 7.simpleDescription

Exercise:

Use the extension keyword to add an attribute for the absolute value of the Double type.

You can use a protocol (Interface) like other named types. For example, declare an object set with Different Types but with the same protocol (interface. When the Protocol (Interface) value is running, external methods are unavailable:

1 let protocolValue: ExampleProtocol = a2 protocolValue. simpleDescription3 // protocolValue. anotherProperty // The running environment of this Code depends on the two examples. In my understanding, if the constant protocolValue complies with the ExampleProtocol protocol, simpleDescription in the protocol can be referenced because it is inside the protocol, anotherProperty is not a method in the protocol, and an error is reported during running. You can try to run it and check the error result. -- By Joe. Huang

Although the ProtocolValue and SimpleClass classes are in the same runtime environment, the compiler places their scopes in ExampleProtocol. That is to say, we cannot intentionally or unintentionally use methods or attributes outside the Protocol (interface.

 

Generics generic

(When it comes to generics, it must be inseparable from generic functions ,~~~ ^_^ ~~~ Hey hey)

Use angle brackets <> to define a generic function or type (name the name in the tip box ):

1 func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[] {2     var result = ItemType[]()3     for i in 0..times {4         result += item5     }6     return result7 }8 repeat("knock", 4)

You can use generics in functions (func) and methods. Similarly, classes, enumerations, and structs can also be used:

1 // optional type 2 enum OptionalValue <T> {3 case None4 case Some (T) 5} 6 var possibleInteger: OptionalValue <Int> =. none7 possibleInteger =. some (100)

Sometimes you need to make some requirements for generics. For example, you need a generic type to implement an interface or inherit from a specific type, and two generic types belong to the same type. Swift useswhereDescribe these requirements:

 1 func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool { 2     for lhsItem in lhs { 3         for rhsItem in rhs { 4             if lhsItem == rhsItem { 5                 return true 6             } 7         } 8     } 9     return false10 }11 anyCommonElements([1, 2, 3], [3])

Exercise:

Modify the anyCommonElements function to return an array with the content of the two sequences.

If this is a simple requirement, You can omit the where keyword. For example, <T where T: Equatable> can be abbreviated as <T: Equatable>.

 

At this point, The Language introduction section in The Swift Programming Language book has been translated, and The detailed guide for further translation will be started in The future. The work volume is huge, I hope that some people who have time can help translate on github. Pai_^

 

Thank you, Swifter-QQ group: 362232993 ~

Github address: https://github.com/Joejo/Swift-lesson-for-chinese

 

 

 

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.