簡體   English   中英

協議方法如何在類中設置變量?

[英]How does a protocol method set a variable in a class?

我正在讀一本Swift OOP書籍,並且在關於協議的一章中。 我知道協議類似於合同,合同具有類可以采用和實現的屬性和方法。 在研究完UITableView教程之后,我注意到UITableViewDataSource協議具有numberOfSections()方法,該方法返回Integer。 此方法還在UITableView實例中設置numberOfSections變量。 我不清楚這是怎么發生的,因為我假設UITableView類與UITableViewDataSource協議是分開的,因此不會設置其任何屬性。 這是示例代碼:

import UIKit

class ItemListDataProvider: NSObject, UITableViewDataSource, UITableViewDelegate 
{        
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
}

這是證明UITableView屬性是由UITableViewDataSource協議的方法設置的測試:

import XCTest
@testable import PassionProject

class ItemListDataProviderTests: XCTestCase 
{        
    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func tests_NumberOfSectionsIsTwo(){

        let sut = ItemListDataProvider()
        let tableView = UITableView()
        tableView.dataSource = sut
        tableView.delegate = sut
        let numberOfSections = tableView.numberOfSections
        XCTAssertEqual(numberOfSections, 2)
    }
}

我了解我們對Apple的API視而不見,但是在嘗試學習Swift OOP時,我想了解幕后情況。

預先感謝您的任何幫助。

我認為這不是設定值。 它定義為getter屬性。 因此,這將是其最接近的定義。

    open var numberOfSections: Int { 
        get { 
             return datasource.numberOfSections
        } 
    }
Consider we are in UITableView Class and when you set the dataSource and delegate of TableView in your any controller class.For example

tableView.dataSource = yourControllerClassObject; 
tableView.delgate = yourControllerClassObject; 

Above code shows that you are passing your controller object to tableView Class and tableView Class holds your controller class object in it's protocol variable of "delegate and dataSource".

When you implement dataSource protocol method in your Controller Class,you are able to call those method from tableView class like below:

class tableView{

self.dataSource.numberOfSections(in tableView: self)

}

above numberOfSctions method returns an integer value of sections that we can store in any variable of class tableView like below.

class tableView{

var numberOfSections = self.dataSource.numberOfSections(in tableView: self)

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM