如何快速地在一个类中调用一个协议?

时间:2018-08-22 08:05:31

标签: swift model-view-controller

我的<groupId>test</groupId> <artifactId>test</artifactId> <version>1.0.0</version> <packaging>jar</packaging> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> </dependency> </dependencies> <properties> <java.version>1.8</java.version> </properties> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> 实现了一个viewcontroller

Protocol

我的主持人实现了第二个import UIKit class FirstScreenViewController: UIViewController, mainViewProtocol { var presenter: mainPresenterProtocol? //Protocol Functions static func showSmallHeadline(textToShow: String) { <#code#> } func showHeadline(textToShow: String) { <#code#> } }

Protocol

如何从我的import Foundation class MainPresenter: mainPresenterProtocol { var screenViewController: mainViewProtocol? //confirms protocol static func presenterProtocolFuncOne() { <#code#> } func presenterProtocolFuncTwo(numOne: Int, numTwo: Int, sucssesMessage: String, failMessage: String) -> String { <#code#> } func presenterProtocolFucThree() -> Bool { <#code#> } } 调用演示者中的功能(通过protocol实现这些功能), 以及如何从演示者中调用viewcontroller(通过viewcontroller实现它们)中的函数?

谢谢!

1 个答案:

答案 0 :(得分:0)

向每个类添加按协议类型引用其他对象的属性。

class FirstScreenViewController: UIViewController, mainViewProtocol {
    var presenter: mainPresenterProtocol?

    // rest of the code
}

class MainPresenter: mainPresenterProtocol {
    var screenViewController: mainViewProtocol?

    // rest of the code
}

在构造两个对象之后分配属性。协议类型后的?使它们成为可选,从而使您可以将分配延迟到两个对象同时存在的时间点。另外,如果可以确定将为属性分配非nil值,则可以将?换为!,这样可以节省大量nil检查和取消引用。

let viewController = FirstScreenViewController()
let mainPresenter = MainPresenter()

viewController.presenter = mainPresenter
presenter.screenViewController = viewController