gpt4 book ai didi

ios - 协议(protocol)方法如何在类中设置变量?

转载 作者:搜寻专家 更新时间:2023-11-01 06:35:54 27 4
gpt4 key购买 nike

我正在阅读一本 Swift OOP 书籍,并且正在阅读有关协议(protocol)的章节。我知道协议(protocol)类似于具有类将采用和实现的属性和方法的契约(Contract)。在完成 UITableView 教程后,我注意到 UITableViewDataSource 协议(protocol)有一个返回 Integer 的 numberOfSections() 方法。此方法还在 UITableView 实例中设置 numberOfSections 变量。我不清楚这是怎么发生的,因为我假设 UITableView 类与 UITableViewDataSource 协议(protocol)是分开的,因此不会设置它的任何属性。这是示例代码:

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 协议(protocol)的方法设置的:

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
}
}

关于ios - 协议(protocol)方法如何在类中设置变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41689832/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com