[Swift] Day13: Protocol, swiftday13 Protocol

Source: Internet
Author: User

[Swift] Day13: Protocol, swiftday13 Protocol
Protocol attribute Protocol

We can define attributes in the Protocol. The following code is incorrect, because the Protocol defines the read-only attribute, but tries to modify its value:

protocol FullyNamed {    var fullName: String { get }}struct Person: FullyNamed{    var fullName: String}let john = Person(fullName: "WHY")john.fullName = "WHY"   // ERROR!
Protocol Synthesis

One protocol can be used by multiple protocolsprotocol<SomeProtocol, AnotherProtocol>This format is called protocol composition ).

protocol Named {    var name: String { get }}protocol Aged {    var age: Int { get }}struct Person: Named, Aged {    var name: String    var age: Int}func wishHappyBirthday(celebrator: protocol<Named, Aged>) {    println("Happy birthday \(celebrator.name) - you're \(celebrator.age)!")}let birthdayPerson = Person(name: "Malcolm", age: 21)wishHappyBirthday(birthdayPerson)
Protocol practice

Let's design a counter and practice the protocol-related content in practice.

First, define a protocol,CounterDataSourceThis Protocol provides an increment value, that is, the value that the counter increases each time. This value can be a fixed value. For example, you can add one at a time or use a method to return different increment values based on different situations. So our definition is as follows:

@objc protocol CounterDataSource {    optional func incrementForCount(count: Int) -> Int    optional var fixedIncrement: Int { get }}

@objcIndicates that the Protocol is optional and can be used to indicate the code exposed to Objective-C, which is only valid for the class.

Next we will define a counter, which containsCounterDataSourceType of data source. Something likeUITableViewDataSourceWe can use this Protocol to obtain the increment step of this count. IfdataSourceImplementedincrementForCountYou can use this method to obtain the step size. Otherwise, you can see if you can get the step size through a fixed value:

@objc class Counter {    var count = 0    var dataSource: CounterDataSource?    func increment() {        if let amount = dataSource?.incrementForCount?(count) {            count += amount        } else if let amount = dataSource?.fixedIncrement? {            count += amount        }    }}

You can use the fixed value method to count:

class ThreeSource: CounterDataSource {    let fixedIncrement = 3}var counter = Counter()counter.dataSource = ThreeSource()for _ in 1...4 {    counter.increment()    println(counter.count)}// 3// 6// 9// 12

You can also use the following methods to count:

class TowardsZeroSource: CounterDataSource {func incrementForCount(count: Int) -> Int {        if count == 0 {            return 0        } else if count < 0 {            return 1        } else {            return -1        }    }}counter.count = -4counter.dataSource = TowardsZeroSource()for _ in 1...5 {    counter.increment()    println(counter.count)}// -3// -2// -1// 0// 0

I have read the official documents for a short time. I will try again later.

References
  • Protocols

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.