为什么我会得到'表达式'(_) - >如果没有更多的上下文错误,_'是不明确的

时间:2016-11-24 02:28:13

标签: swift mvvm closures

我正在调整example of MVVM到我的应用,我正在获得'表达式'(_) - >即使我的代码结构与示例完全相同,_'也是不明确的,没有更多的上下文'错误。这是相关代码(Swift 2.3):

视图控制器:

class CalculatorViewController: UIViewController, CalculatorViewModelDelegate, UITextFieldDelegate, DismissalDelegate {

  let dataManager = LiftEventDataManager()

  @IBOutlet weak var liftNameButtonView: UIView!
  @IBOutlet weak var liftNameButton: UIButton!
  @IBOutlet weak var repsLabel: UILabel!
  @IBOutlet weak var repetitionsField: UITextField!
  @IBOutlet weak var weightLabel: UILabel!
  @IBOutlet weak var weightLiftedField: UITextField!
  @IBOutlet weak var oneRepMaxField: UILabel!
  @IBOutlet weak var units: UILabel!

  var weightLifted: String {
    return weightLiftedField.text!
  }

  var repetitions: String {
    return repetitionsField.text!
  }

  var viewModel: CalculatorViewModelProtocol! {
    didSet {

// This is were I get the 'Expression type '(_) -> _' is ambiguous without more context' error
      self.viewModel.weightLiftedDidChange = { [unowned self] viewModel in
        self.weightLiftedField.text = viewModel.greeting
      }
    }
  }

 override func viewDidLoad() {

    super.viewDidLoad()

    let viewModel = CalculatorViewModel(delegate: self)

    self.viewModel = viewModel

    weightLiftedField.addTarget(self, action: #selector(didChangeWeightLifted), forControlEvents: .EditingDidEndOnExit)
   }

  func didChangeWeightLifted() {
    viewModel!.weightLifted = self.weightLifted
    }
  }

我的观点模型:

protocol CalculatorViewModelProtocol: class {

    weak var delegate: CalculatorViewModelDelegate? { get set }
    var liftName: String? { get set }
    var weightLifted: String? { get set }
    var repetitions: String? { get set }
    var oneRepMax: String? { get set }
    var units: String? { get set }
    var date: String? { get set }

    // the type is clearly defined here
    var weightLiftedDidChange: ((CalculatorViewModelProtocol) -> ())? { get set }

    var repetitionsDidChange: ((CalculatorViewModelProtocol) -> ())? { get set }
    //var oneRepMaxDidChange: ((CalculatorViewViewModel) -> ()) { get set }
    func calculateOneRepMax(weightLifted: Double, repetitions: UInt8)
}

class CalculatorViewModel: CalculatorViewModelProtocol, LiftEventDataManagerDelegate {

    let calculator = CalculatorBrain()

    private let dataManager = LiftEventDataManager()

    var liftName: String?
    var weightLifted: String?
    var repetitions: String?
    var oneRepMax: String?
    var units: String?
    var date: String?
    var weightLiftedDidChange: ((CalculatorViewModelProtocol) -> ())?
    var repetitionsDidChange: ((CalculatorViewModelProtocol) -> ())?

    func changeWeightLifted(weight: String) {
        weightLifted = weight
    }
}

Xcode似乎在告诉我它无法推断出self.viewModel.weightLiftedDidChange的类型,但我在viewModel类中指定了类型。

关于这个错误有很多线索,但是我没有找到一个有帮助的帖子,而且我已经搜索过苹果公司的文档,但没有任何乐趣。

0 个答案:

没有答案