据我所知,通常我无法实例化协议。
但是,如果我在协议中包含一个初始化程序,那么编译器肯定知道当结构或类稍后使用该协议时,它将有一个可以使用的 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)
}
}
}
}
该行:
return Puzzle(problem: problem, solution: solution)
给出错误:协议类型“Puzzle”无法实例化
想象协议是形容词。Movable
说你可以move
it, Red
说它有color = "red"
...但他们没有说是什么it是。你需要一个名词。一辆红色的可移动的汽车。即使细节很少,您也可以实例化一辆汽车。您无法实例化红色。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)