快速地,为什么有初始化器时不能实例化协议? [英] In swift, why can't I instantiate a protocol when it has an initialiser?

查看:96
本文介绍了快速地,为什么有初始化器时不能实例化协议?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道通常我无法实例化协议. 但是,如果我在协议中包括一个初始化程序,那么编译器肯定会知道,当该协议稍后在结构或类中使用时,它将具有可以使用的初始化吗? 我的代码如下和行:

I understand that generally I cannot instantiate a protocol. But if I include an initialiser in the protocol then surely the compiler knows that when the protocol is used by a struct or class later, it will have an init which it can use? My code is as below and line:

protocol Solution {
  var answer: String { get }
}

protocol Problem {
  var pose: String { get }
}

protocol SolvableProblem: Problem {
  func solve() -> Solution?
}

protocol ProblemGenerator {
  func next() -> SolvableProblem
}

protocol Puzzle {
  var problem: Problem { get }
  var solution: Solution { get }

  init(problem: Problem, solution: Solution)
}

protocol PuzzleGenerator {
  func next() -> Puzzle
}

protocol FindBySolvePuzzleGenerator: PuzzleGenerator {
  var problemGenerator: ProblemGenerator { get }
}

extension FindBySolvePuzzleGenerator {
  func next() -> Puzzle {
    while true {
      let problem = problemGenerator.next()
      if let solution = problem.solve() {
        return Puzzle(problem: problem, solution: solution)
      }
    }
  }
}

该行:

return Puzzle(problem: problem, solution: solution)

给出错误:协议类型'Puzzle'无法实例化

gives error: Protocol type 'Puzzle' cannot be instantiated

推荐答案

想象协议是形容词. Movable表示可以moveRed表示具有color = "red" ...,但是他们没有说 是什么.您需要一个名词.一辆红色的可移动汽车.即使细节不多,您也可以实例化Car.您无法实例化红色.

Imagine protocols are adjectives. Movable says you can move it, Red says it has color = "red"... but they don't say what it is. You need a noun. A Red, Movable Car. You can instantiate a Car, even when low on details. You cannot instantiate a Red.

这篇关于快速地,为什么有初始化器时不能实例化协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆