在 swift 中,为什么我不能实例化具有初始化程序的协议?

Ada*_*hus 6 protocols instantiation swift

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

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)
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

线路:

return Puzzle(problem: problem, solution: solution)
Run Code Online (Sandbox Code Playgroud)

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

Ama*_*dan 7

想象协议是形容词。Movable说,你可以move它,Red说它有color = "red"......但他们没有说什么是。你需要一个名词。一辆红色的可移动汽车。您可以实例化汽车,即使细节很少。你不能实例化一个红色。