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”
想象协议是形容词。Movable
说,你可以move
它,Red
说它有color = "red"
......但他们没有说什么它是。你需要一个名词。一辆红色的可移动汽车。您可以实例化汽车,即使细节很少。你不能实例化一个红色。
归档时间: |
|
查看次数: |
1436 次 |
最近记录: |