Swift 4.3-在2个文件之间传递数据的协议

问题描述 投票:0回答:2

我正在努力了解协议的工作方式。我有2个文件,想要使用协议来传递数据...这是我在做什么:

在ViewController.swift中

protocol workingProtocol { func myFunc(strValue: String)}    

class ViewController: UIViewController {
  var interactor = workingProtocol
  @objc func doneBtn() {
     interactor.myFunc(strValue: "str")
  }
}

在Interactor.swift中

class Interactor {
 func myFunc(strValue: String) {
   print(strValue)
 }
}

不是从Interactor.swift打印数据

swift swift-protocols
2个回答
0
投票

很遗憾,我看不到如何注入交互类,而且您的代码在语法上也有问题。它的外观如下:

protocol WorkingProtocol: AnyObject {
 func myFunc(strValue: String)
}    

final class ViewController: UIViewController {

  var interactor: WorkingProtocol

  @objc func doneBtn() {
     interactor.myFunc(strValue: "str")
  }
}

final class Interactor: WorkingProtocol {

 func myFunc(strValue: String) {
   print(strValue)
 }
}

以及如何使用:

let interactor: WorkingProtocol = Interactor()
let vc = ViewController(interactor: interactor)

vc.doneBtn()

0
投票

协议定义了一种功能的方法,属性和其他要求的blueprint

这是一个基于代码的工作方式示例

protocol ProtocolName {
 func functionName(strValue: String)
}

class ViewController {
  var interactor: ProtocolName? = nil

  @objc
  fileprivate func doneBtn() {
    interactor?.functionName(strValue: "Passing data to interactor using protocols")
  }
}

class Interactor: ProtocolName {
  func functionName(strValue: String) {
    print("Showing value\n", strValue)
  }
}

let interactor = Interactor()
let viewController = ViewController()
viewController.interactor = interactor
viewController.doneBtn()

另一个例子:

protocol ProtocolName {
 func functionName(strValue: String)
}

class ViewController1 {
  let interactor = Interactor1()

  /// Init or viewDidLoad() if you're using ViewController classes.
  init() {
    interactor.delegate = self
  }
}

extension ViewController1: ProtocolName {
  func functionName(strValue: String) {
    print("Printing the value: \(strValue)")
  }
}

class Interactor1 {
  var delegate: ProtocolName?

  func someAction() {
    delegate?.functionName(strValue: "Executed action in interactor.")
  }
}

let vc = ViewController1()
vc.interactor.someAction()
© www.soinside.com 2019 - 2024. All rights reserved.